Shell script with options

scripting

For more professional like scripting is nice to use options, where we can do different work with one script just using it. In this article I will show you, how to write script, where we can switch what to do using options -h for help, or -e for echoing “hello world”. Of course, this is just example and we can use it for more complex work than just hello world :).

The main point of this script is getopts utility which retrieve options and option-arguments from a list of parameters.

#!/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


How we will use our script? There are some examples, also we can see how script works when we do not use any options, or we use wrong one.

# ./args.sh
Missing options!
(run ./args.sh -h for help)

#
# ./args.sh -h
Usage:
args.sh -h
args.sh -e

   -e     to execute echo "hello world"
   -h     help (this output)
#
# ./args.sh -e
Hello world
#
# ./args.sh -t
./args.sh: illegal option -- t
#

Leave a Reply