局部变量改变了鞭尾行为

时间:2017-09-13 08:03:08

标签: bash whiptail

我有这个脚本:

#!/bin/bash

menu()
{
while true; do
    opt=$(whiptail \
        --title "Select an item" \
        --menu "" 20 70 10 \
        "1 :" "Apple" \
        "2 :" "Banana" \
        "3 :" "Cherry" \
        "4 :" "Pear" \
        3>&1 1>&2 2>&3)

    rc=$?

    echo "rc=$rc opt=$opt"

    if [ $rc -eq 255 ]; then # ESC
        echo "ESC"
        return
    elif [ $rc -eq 0 ]; then # Select/Enter
        case "$opt" in
            1\ *) echo "You like apples"; return ;;
            2\ *) echo "You go for bananas"; return ;;
            3\ *) echo "I like cherries too"; return ;;
            4\ *) echo "Pears are delicious"; return ;;
            *) echo "This is an invalid choice"; return ;;
        esac
    elif [ $rc -eq 1 ]; then # Cancel
        echo "Cancel"
        return
    fi
done
}

menu

当我按下ESC按钮时,输出符合预期:

rc=255 opt=
ESC

现在,通过使opt成为local变量,行为就不同了:

...
local opt=$(whiptail \
...

输出:

rc=0 opt=
This is an invalid choice

有人可以解释一下吗?

2 个答案:

答案 0 :(得分:2)

$?正在获取local命令的返回码。尝试使用local命令和赋值单独的语句:

local opt
opt=$(whiptail ...

答案 1 :(得分:0)

我找到this wonderful tool检查bash脚本是否存在可能的错误......

$ shellcheck myscript

Line 6:
    local opt=$(whiptail \
          ^-- SC2155: Declare and assign separately to avoid masking return values.

$