How to write Unix shell scripts with options?

Yes, you can use the shell built-in getopts, or the stand-alone getopt for this purpose.


this is the way how to do it in one script:

#!/usr/bin/sh
#
# Examlple of using options in scripts
#

if [ $# -eq 0 ]
then
        echo "Missing options!"
        echo "(run $0 -h for help)"
        echo ""
        exit 0
fi

ECHO="false"

while getopts "he" OPTION; do
        case $OPTION in

                e)
                        ECHO="true"
                        ;;

                h)
                        echo "Usage:"
                        echo "args.sh -h "
                        echo "args.sh -e "
                        echo ""
                        echo "   -e     to execute echo \"hello world\""
                        echo "   -h     help (this output)"
                        exit 0
                        ;;

        esac
done

if [ $ECHO = "true" ]
then
        echo "Hello world";
fi

click here for source


$ cat stack.sh 
#!/bin/sh
if  [[ $1 = "-o" ]]; then
    echo "Option -o turned on"
else
    echo "You did not use option -o"
fi

$ bash stack.sh -o
Option -o turned on

$ bash stack.sh
You did not use option -o

FYI:

$1 = First positional parameter
$2 = Second positional parameter
.. = ..
$n = n th positional parameter

For more neat/flexible options, read this other thread: Using getopts to process long and short command line options

Tags:

Shell