Multiple argument arguments using getopts (bash)

I am trying to handle command line arguments with getopts in bash. One of the requirements is to process an arbitrary number of argument arguments (without the use of quotation marks).

1st example (only captures 1st argument)

madcap:~/projects$ ./getoptz.sh -sabc -s was triggered Argument: a 

Second example (I want it to behave this way, but without specifying an argument

 madcap:~/projects$ ./getoptz.sh -s "abc" -s was triggered Argument: abc 

Is there any way to do this?

Here is the code that I have now:

 #!/bin/bash while getopts ":s:" opt; do case $opt in s) echo "-s was triggered" >&2 args="$OPTARG" echo "Argument: $args" ;; \?) echo "Invalid option: -$OPTARG" >&2 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done 
+6
source share
2 answers

I think you want to get a list of values ​​from one option. To do this, you can repeat this option as many times as necessary and add it to the array.

 #!/bin/bash while getopts "m:" opt; do case $opt in m) multi+=("$OPTARG");; #... esac done shift $((OPTIND -1)) echo "The first value of the array 'multi' is '$multi'" echo "The whole list of values is '${multi[@]}'" echo "Or:" for val in "${multi[@]}"; do echo " - $val" done 

The conclusion will be:

 $ /tmp/t The first value of the array 'multi' is '' The whole list of values is '' Or: $ /tmp/t -m "one arg with spaces" The first value of the array 'multi' is 'one arg with spaces' The whole list of values is 'one arg with spaces' Or: - one arg with spaces $ /tmp/t -m one -m "second argument" -m three The first value of the array 'multi' is 'one' The whole list of values is 'one second argument three' Or: - one - second argument - three 
+11
source

You can analyze the command line arguments yourself, but the getopts command cannot be configured to recognize multiple arguments for a single option. fedorqui recommendation is a good alternative.

Here is one way to parse this option yourself:

 while [[ "$*" ]]; do if [[ $1 = "-s" ]]; then # -s takes three arguments args="$2 $3 $4" echo "-s got $args" shift 4 fi done 
+3
source

Source: https://habr.com/ru/post/943509/


All Articles