Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing for command line args in bash

Tags:

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?

like image 306
MK. Avatar asked Mar 14 '11 17:03

MK.


People also ask

How do I find bash command line arguments?

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.

How do I find command line arguments?

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.

What is the test command in bash?

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.


1 Answers

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 
like image 162
Dennis Williamson Avatar answered Oct 05 '22 23:10

Dennis Williamson