In Shell scripting, getopts could be used to retrieve command arguments. There is a similar command, getopt which could also be used, but getopts is more powerful.
Here follows an example of using getopts:
[code]
#
# Extracts the parameters from the command line
#
while getopts :f:m:w: TOKEN 2> /dev/null
do
case $TOKEN in
f) fileConfigPath=$OPTARG
;;
m) mediaConfigPath=$OPTARG
;;
w) workArea=$OPTARG
;;
\?) usage
exit 1
;;
esac
done
[code]
What one needs to be careful is that getopts accepts only one char arguments. So you cannot specify -wc option; it will simply not work.
The colon after an option means that an argument is required after that option. so c: means that the program will need to be invoked like program -c argument-value. If I didn't specify the colon (:) that I could have called the program with program -c
The color (:) before the list of arguments f:m:w: (e.g. the string :f:m:w:) tells getopts that if an unspecified option is passed, to set TOKEN to ?. This can be useful in situation when you want your program to be a bit more relaxed in case of additional, not required arguments, or you can make your program more strict (like the example above) and have it to exit with an error code in case of any unsolicited options.
Happy technology to everyone
Recent Comments