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 way of testing if --foo
is present as one of the arguments, not necessarily the first one?
Get Values of All the Arguments in Bash We can use the $* or the $@ command to see all values given as arguments. This code prints all the values given as arguments to the screen with both commands.
First of all, to check if there is an argument, you should use the argc variable of the main(int argc, char** argv) , which indicates the length of your argv array.
In bash shell, the test command compares one element against another and returns true or false. In bash scripting, the test command is an integral part of the conditional statements that control logic and program flow.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With