2

My apology for not being able to find such a seemingly trivial thing myself.

I need to pass more than one boolean parameter to shell script (Bash) as follows:

./script --parameter1 --parameter2

and so on.

All are to be considered true if set.

In the beginning of the script, I use set -u.

Normal parameter with value passing I currently do as follows:

# this script accepts the following arguments:
# 1. mode
# 2. window

while [[ $# > 1 ]]
do

    cmdline_argument="$1"

    case $cmdline_argument in

        -m|--mode)

            mode="$2"
            shift

        ;;

        -w|--window)

            window="$2"
            shift

        ;;

    esac

    shift

done

I would like to add something like

    -r|--repeat)

        repeat=true

        shift

    ;;

I do not understand why it does not work as expected.

It exits immediately with error:

./empire: line 450: repeat: unbound variable

Where the line 450 is:

if [ "$repeat" == true ];
11
  • Can you clarify how it fails? Is it because you're missing a shift? Commented Jun 17, 2017 at 2:21
  • @GordonDavisson I tried it with and without shift. Commented Jun 17, 2017 at 2:30
  • 1
    You're using set -u, aren't you? Commented Jun 17, 2017 at 2:53
  • @CharlesDuffy Yes. Commented Jun 17, 2017 at 2:54
  • 1
    See BashFAQ #112. And on a related note, definitely read BashFAQ #105 before using set -e. Commented Jun 17, 2017 at 2:56

1 Answer 1

6

When you use set -u, it's an error to dereference any variable that hasn't had a value explicitly assigned.

Thus, you need to set repeat=0 (or repeat=false) at the top of your script, or to use a dereference method that has an explicit default behavior when the value is unset; see BashFAQ #112.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.