局部变量改变鞭尾行为

local variable changes whiptail behaviour

我有这个脚本:

#!/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

谁能解释一下?

$? 正在获取 local 命令的 return 代码。尝试使 local 命令和分配单独的语句:

local opt
opt=$(whiptail ...

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

$ shellcheck myscript

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

$