|
| 1 | ++++ |
| 2 | +title = "Bash: Positional parameters" |
| 3 | ++++ |
| 4 | + |
| 5 | +To parse positional parameters in Bash, you can use the `getopts` builtin. |
| 6 | + |
| 7 | +It's syntax is `getopts optstring name`, where `optstring` contains the option characters to be recognized. If a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. `name` is the name of the variable to put the current option in. The value of an argument is stored in `OPTARG`. |
| 8 | + |
| 9 | +See [`man bash`](https://www.man7.org/linux/man-pages/man1/bash.1.html) for more information. |
| 10 | + |
| 11 | +To add support for long option names, you can make use of the `set` builtin to add a single letter option to the positional parameters if a long option is found. Here's an example of that: |
| 12 | + |
| 13 | +```bash |
| 14 | +function handle_args() |
| 15 | +{ |
| 16 | + for arg in "$@"; do |
| 17 | + shift |
| 18 | + case "$arg" in |
| 19 | + "--debug") set -- "$@" '-d' ;; |
| 20 | + "--help") set -- "$@" '-h' ;; |
| 21 | + "--ignore") set -- "$@" '-i' ;; |
| 22 | + "--name") set -- "$@" '-n' ;; |
| 23 | + "--publish") set -- "$@" '-p' ;; |
| 24 | + *) set -- "$@" "$arg" ;; |
| 25 | + esac |
| 26 | + done |
| 27 | + |
| 28 | + while getopts ":dhin:p" opt; do |
| 29 | + case $opt in |
| 30 | + d) option_debug_enabled=true ;; |
| 31 | + h) |
| 32 | + echo "$0 usage:" |
| 33 | + echo " -d, --debug Enable debug messages" |
| 34 | + echo " -h, --help Show the usage message" |
| 35 | + echo " -i, --ignore Ignore existing packages" |
| 36 | + echo " -n, --name Build the package with this name" |
| 37 | + echo " -p, --publish Publish the packages" |
| 38 | + exit 0 |
| 39 | + ;; |
| 40 | + i) option_ignore_enabled=true ;; |
| 41 | + n) option_package_name="$OPTARG" ;; |
| 42 | + p) option_publish_enabled=true ;; |
| 43 | + *) warn "unknown option $OPTARG" ;; |
| 44 | + esac |
| 45 | + done |
| 46 | +} |
| 47 | +``` |
0 commit comments