testing for command line args in bash
I am testing to see if the first argument to my script is --foo
if [ $# > 1 ]
then
if [[ "$1" = "--foo" ]]
then
echo "foo is set"
foo = 1
fi
fi
if [[ -n "$foo"]]
then
#dosomething
fi
Can someone pleaset tell me what is the bash wa开发者_C百科y of testing if --foo
is present as one of the arguments, not necessarily the first one?
You should use the external getopt
utility if you want to support long options. If you only need to support short options, it's better to use the the Bash builtin getopts
.
Here is an example of using getopts
(getopt
is not too much different):
options=':q:nd:h'
while getopts $options option
do
case $option in
q ) queue=$OPTARG;;
n ) execute=$FALSE; ret=$DRYRUN;; # do dry run
d ) setdate=$OPTARG; echo "Not yet implemented.";;
h ) error $EXIT $DRYRUN;;
\? ) if (( (err & ERROPTS) != ERROPTS ))
then
error $NOEXIT $ERROPTS "Unknown option."
fi;;
* ) error $NOEXIT $ERROARG "Missing option argument.";;
esac
done
shift $(($OPTIND - 1))
Not that your first test will always show a true
result and will create a file called "1" in the current directory. You should use (in order of preference):
if (( $# > 1 ))
or
if [[ $# -gt 1 ]]
or
if [ $# -gt 1 ]
Also, for an assignment, you can't have spaces around the equal sign:
foo=1
As Dennis noted, getopt
and getopts
are the standard ways for parsing command line arguments. For an alternative way, you could use the $@ special variable, which expands to all of the command line arguments. So, you could test for it using the wildcard in your test:
#!/usr/bin/env bash
if [[ $@ == *foo* ]]
then
echo "You found foo"
fi
That said, you'll be better off if you figure out getopt sooner rather than later.
精彩评论