I am trying to make a shell script which is designed to be run like this:
script.sh -t application
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:
script.sh
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:
FLAG="application"
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.
Use
$#
to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:Next, check if
$1
equals-t
, otherwise an unknown flag was used:Finally store
$2
inFLAG
:Note:
usage()
is some function showing the syntax. For example:Here is a generalized simple command argument interface you can paste to the top of all your scripts.
By running the command:
The output will be this:
Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.
Allowing me and now you to never deal with bash arguemnt parsing again!
Try shFlags -- Advanced command-line flag library for Unix shell scripts.
http://code.google.com/p/shflags/
It is very good and very flexible.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.
DEFINE_string: takes any input, and intreprets it as a string.
DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.
DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.
DEFINE_integer: takes an input and intreprets it as an integer.
SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing
EXAMPLE USAGE:
Note: I took this text from shflags documentation
You should read this getopts tutorial.
Example with
-a
switch that requires an argument :Like greybot said(
getopt
!=getopts
) :