user3863616
user3863616

Reputation: 195

parameters and switches in bash script

I need to modify one of my scripts. Until now it has two obligatory parameters which point out to version of update and database where this update is going to be applied

./script.sh version db_name

Now I want to add two new optional parameters, in fact I should call it switches. These switches extend it to : 1. before install stop (or not) my web server 2. install also some new files to filesystem Both of the returns bool value. All details are inside the script. So i expect something like:

./script.sh version db_name -stopweb  -copyfiles

I have figured out getopts is suitable command. The problem is how to "join" parameters (obligatory) and switches (optional) together. I really can't get it :( Could you give me some hints please.

Upvotes: 0

Views: 9043

Answers (1)

Chris Maes
Chris Maes

Reputation: 37762

You should consider using getopts. Here is a sample of what I use for option parsing in my bash scripts:

TEMP=$(getopt -o dp:v --long dev,publish:,verbose -- "$@")

# Note the quotes around '$TEMP': they are essential!
eval set -- "$TEMP"

#default values
DEV=0
VERBOSE=
while true; do
    case "$1" in
        -d | --dev ) DEV=1; shift ;;
        -p | --publish ) PUBLISH="$2" ; shift 2;;
        -v | --verbose ) VERBOSE="-v" ; shift ;;
        -- ) if [ -n "$2" ]
            then
                ARGUMENT1=$2
                if [ -n "$3" ]
                then
                    ARGUMENT2=$3
                    if [ -n "$4" ]
                    then
                        shift 3
                        echo "Unexpected options: \"$@\" . exiting."
                        exit 1;
                    fi
                fi
            fi
            shift 2; break;;
        * ) break ;;
    esac
done

# you can add some checks here that ARGUMENT1 and ARGUMENT2 were effectively set, if they are mandatory

some features:

  • use short and long options
  • some options need an argument
  • use some optional arguments (one in this case), that doesn't start with -

NOTE : in order for getopts to be able to distinguish -dv being two short options and --dev being a long option; all your long options should start with two hyphens.

Upvotes: 5

Related Questions