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?
getopt is your friend.. a simple example:
There should be various examples in your /usr/bin directory.
If you're familiar with Python argparse, and don't mind calling python to parse bash arguments, there is a piece of code I found really helpful and super easy to use called argparse-bash https://github.com/nhoffman/argparse-bash
Example take from their example.sh script:
Another alternative would be to use something like the below example which would allow you to use long --image or short -i tags and also allow compiled -i="example.jpg" or separate -i example.jpg methods of passing in arguments.
This is the idiom I usually use:
Key points are:
$#
is the number of argumentsThis example uses Bash's built-in
getopts
command and is from the Google Shell Style Guide: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.
I think this would serve as a simpler example of what you want to achieve. There is no need to use external tools. Bash built in tools can do the job for you.
This will allow you to use flags so no matter which order you are passing the parameters you will get the proper behavior.
Example :
Output :
You can add this function to your profile or put it inside of a script.
Thanks!
Edit : Save this as a a file and then execute it as
yourfile.sh -last "Adios" -first "Hola"