"unbound variable"从shell脚本命令行读取布尔参数

Lin*_*eak 2 bash shell parameter-passing

我为自己无法找到这样一个看似微不足道的事情而道歉.

我需要将多个布尔参数传递给shell脚本(Bash),如下所示:

./script --parameter1 --parameter2
Run Code Online (Sandbox Code Playgroud)

等等.

true如果设置,则应考虑所有因素.

在脚本的开头,我使用set -u.

值传递的正常参数我目前做如下:

# 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
Run Code Online (Sandbox Code Playgroud)

我想补充类似的东西

    -r|--repeat)

        repeat=true

        shift

    ;;
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它不能按预期工作.

它立即退出并出现错误:

./empire: line 450: repeat: unbound variable
Run Code Online (Sandbox Code Playgroud)

第450行是:

if [ "$repeat" == true ];
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 6

使用时set -u,取消引用任何未明确赋值的变量是错误的.

因此,您需要在脚本的顶部设置repeat=0(或repeat=false),或者在取消设置值时使用具有显式默认行为的取消引用方法; 见BashFAQ#112.