shell

How to write Unix shell scripts with options?


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.


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