6

Below is the script. When I ran this with command

./scriptname --deploy --uglify"

I'm getting result for echo "$deploy" as true. But it should be uglify right since deploy=$2

#!/bin/bash

deploy=true
uglify=true

while (( $# > 1 )); do 
    case $1 in
    --deploy) deploy="$2" echo "$deploy";;
    --uglify) uglify="$2";;
    *) break;
    esac; shift 2
done
Inian
  • 80,270
  • 14
  • 142
  • 161
karthi keyan
  • 63
  • 1
  • 3

3 Answers3

5

you mean something like this:

#!/bin/bash

deploy=false
uglify=false

while (( $# >= 1 )); do 
    case $1 in
    --deploy) deploy=true;;
    --uglify) uglify=true;;
    *) break;
    esac;
    shift
done

echo "deploy: $deploy"
echo "uglify: $uglify"

examples

$ ./scriptname
deploy: false
uglify: false


$ ./scriptname --deploy
deploy: true
uglify: false


$ ./scriptname --uglily
deploy: false
uglify: true

$ ./scriptname --depoly --uglily
deploy: true
uglify: true
UtLox
  • 3,744
  • 2
  • 10
  • 13
1

While dealing with this I came up with the following. We encapsulate all the procedure inside a function that takes all the arguments given to the script. Then, it iterates over all the arguments and whenever it find one that starts with double hyphen --arg1 it assigns the following argument arg2 to a global variable with the name of the first argument arg1="arg2". Next, it shifts the arguments' positions until it finish with all arguments.

#------ arguments_test.sh ------
#!/bin/bash
pararser() {
    # Define default values
    name=${name:-"name_def"}
    lastName=${lastName:-"lastName_def"}

    # Assign the values given by the user
    while [ $# -gt 0 ]; do
        if [[ $1 == *"--"* ]]; then
            param="${1/--/}"
            declare -g $param="$2"
        fi
        shift
    done

}


pararser $@

echo "My name is " $name $lastName

In this way we can define default values if they are not passed.

$ arguments_test.sh
> My name is name_def lastName_def
$ arguments_test.sh --name Foo --lastName Bar
> My name is Foo Bar

Some references

  • The main procedure was found here.
  • More about passing all the arguments to a function here.
  • More info regarding default values here.
  • More info about declare do $ bash -c "help declare".
  • More info about shift do $ bash -c "help shift".
H. Sánchez
  • 566
  • 6
  • 14
0

The variables in the command are all expanded before anything is executed, so the old value of $deploy is used in the expansion. So it's executing

deploy="--uglify" echo "true"

Change that line to:

    --deploy) deploy="$2"; echo "$deploy";;

If you don't want to change the value of deploy in the script process, you can run echo in a subprocess:

    --deploy) deploy="$2" bash -c 'echo "$deploy"';;
Barmar
  • 741,623
  • 53
  • 500
  • 612