-1
$ cat test15.sh  
#!/bin/bash  
# extracting command line options as parameters  
#  
echo  
while [ -n "$1" ]  
do  
    case "$1" in  
    -a) echo "Found the -a option" ;;  
    -b) echo "Found the -b option" ;;  
    -c) echo "Found the -c option" ;;  
     *) echo "$1 is not an option" ;;
esac  
shift  
done  
$  
$ ./test15.sh -a -b -c -d

Found the -a option  
Found the -b option  
Found the -c option  
-d is not an option 
$  

-d represents debug or delete as a command line option. So why is it not an option when we included it in options on command line for some script?

3

-d represents whatever it is programmed to represent, which will not necessarily be delete or debug. In curl for example -d is the option for data. In your script -d is not a valid option. Your options are -a, -b, and -c. All of which essentially do nothing.

while [ -n "$1" ]  
do  
    case "$1" in  
        -a) echo "Found the -a option" ;;  
        -b) echo "Found the -b option" ;;  
        -c) echo "Found the -c option" ;;  
         *) echo "$1 is not an option" ;;
    esac  
shift  
done  

To add support for -d you must add it to your case statement like the following:

while [ -n "$1" ]  
do  
    case "$1" in  
        -a) echo "Found the -a option" ;;  
        -b) echo "Found the -b option" ;;  
        -c) echo "Found the -c option" ;;  
        -d) echo "Found the -d option" ;;
         *) echo "$1 is not an option" ;;
    esac  
shift  
done  

A better way to handle command line options would be with getopts which would look something like the following:

while getopts abcd opt; do 
    case $opt in
        a) echo "Found the -a option";;
        b) echo "Found the -b option";;
        c) echo "Found the -c option";;
        d) echo "Found the -d option";;
        *) echo "Error! Invalid option!" >&2;;
    esac
done

abcd is the list of expected arguments.
a - check for option -a without parameters; gives error on unsupported options.
a: - check for option -a with parameter; gives errors on unsupported options. The parameter would be set to the OPTARG variable.
abcd - check for options -a, -b, -c, -d; gives errors on unsupported options.
:abcd - check for options -a, -b, -c, -d; silences errors on unsupported options.

opt is the variable the current parameter will be set to (also used in the case statement)

  • 1
    Using getopts is preferred as it also stops processing at the first non-option argument (or at --), which makes it easier to handle e.g. file operands too. – Kusalananda Mar 18 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.