Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get arguments with flags in Bash

Tags:

bash

shell

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?

like image 326
Stann Avatar asked Aug 15 '11 19:08

Stann


People also ask

How do I get command-line arguments in bash?

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.

What does [- Z $1 mean in bash?

$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.

How do I add a flag in bash?

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.).

What is $@ in bash?

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.


1 Answers

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:

  • the while condition is a lot more readable and shows what the accepted options are
  • cleaner code; no counting the number of parameters and shifting
  • you can join options (e.g. -a -b -c-abc)

However, a big disadvantage is that it doesn't support long options, only single-character options.

like image 144
Dennis Avatar answered Oct 26 '22 22:10

Dennis