Skip to content
Advertisement

Bash Shell Script – Check for a flag and grab its value

I am trying to make a shell script which is designed to be run like this:

JavaScript

Firstly, in my script I want to check to see if the script has been run with the -t flag. For example if it has been run without the flag like this I want it to error:

JavaScript

Secondly, assuming there is a -t flag, I want to grab the value and store it in a variable that I can use in my script for example like this:

JavaScript

So far the only progress I’ve been able to make on any of this is that $@ grabs all the command line arguments but I don’t know how this relates to flags, or if this is even possible.

Advertisement

Answer

You should read this getopts tutorial.

Example with -a switch that requires an argument :

JavaScript

Like greybot said(getopt != getopts) :

The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement