I know that I can easily get positioned parameters like this in bash:
$0
or $1
I want to be able to use flag options like this to specify for what each parameter is used:
mysql -u user -h host
What is the best way to get -u param
value and -h param
value by flag instead of by position?
We can pass command-line arguments at our convenience in a positional way or with flags. Moreover useful concepts like $@ (array of all the parameters), $# (by calculating input size) are available and with that, we can iterate in the “for” or “while” loops, we can access the arguments.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
Adding flags can be done in many different ways, the most common way is probably using getopts . However, in that case your a limited to using only short flags ( -f instead of --flag , for example.).
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
This example uses Bash's built-in getopts
command and is from the Google Shell Style Guide:
a_flag='' b_flag='' files='' verbose='false' print_usage() { printf "Usage: ..." } while getopts 'abf:v' flag; do case "${flag}" in a) a_flag='true' ;; b) b_flag='true' ;; f) files="${OPTARG}" ;; v) verbose='true' ;; *) print_usage exit 1 ;; esac done
Note: If a character is followed by a colon (e.g. f:
), that option is expected to have an argument.
Example usage: ./script -v -a -b -f filename
Using getopts has several advantages over the accepted answer:
-a -b -c
→ -abc
)However, a big disadvantage is that it doesn't support long options, only single-character options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With