Question

I don't know whether it's possible, but I want to write shell scripts that act like regular executables with options. As a very simple example, consider a shell script foo.sh that is configured to be executable:

    ./foo.sh
    ./foo.sh -o

and the code foo.sh works like

    #!/bin/sh
    if  ## option -o is turned on
        ## do something
    else
        ## do something different
    endif

Is it possible and how to do that? Thanks.

Was it helpful?

Solution

$ 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

OTHER TIPS

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

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

You can iterate over the arguments to and read the options in any order. Here is an example. For a script using this code see - script example

#Example
OPTION_1=""
option_array[0]="1"
option_array[1]="2"

options="$@"


set_options(){
    prev_option=""

    for option in $options;
    do
        case $prev_option in
            "-t" )
                OPTION_1=$option
            ;;
            "-d" )
                option_array+=("$option")
            ;;
            "-g" )

                option_array_2+=("$option")
            ;;

        esac

        prev_option="$option"

    done

}

function test()
{
    set_options

    echo $OPTION_1
    echo ${option_array[*]}
    echo ${option_array_2[*]}

}


test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top