【问题标题】:"unbound variable" reading a boolean parameter from shell script command line“未绑定变量”从 shell 脚本命令行读取布尔参数
【发布时间】:2017-06-17 02:13:27
【问题描述】:

我很抱歉自己没能找到这么看似微不足道的东西。

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

./script --parameter1 --parameter2

等等。

如果设置,所有都将被视为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

我想添加类似的东西

    -r|--repeat)

        repeat=true

        shift

    ;;

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

它立即退出并出现错误:

./empire: line 450: repeat: unbound variable

第 450 行在哪里:

if [ "$repeat" == true ];

【问题讨论】:

  • 你能解释一下它是如何失败的吗?是因为你错过了shift
  • @GordonDavisson 我试过有没有shift
  • 你在使用set -u,不是吗?
  • @CharlesDuffy 是的。
  • BashFAQ #112。在相关说明中,一定在使用 set -e 之前阅读 BashFAQ #105

标签: bash shell parameter-passing


【解决方案1】:

当您使用set -u 时,取消引用任何没有显式分配值的变量是错误的。

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

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 2013-10-19
    • 1970-01-01
    • 2015-04-19
    • 2011-10-16
    • 1970-01-01
    • 2014-08-22
    • 2014-08-11
    • 2015-03-30
    相关资源
    最近更新 更多