1

我有这个脚本:

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

有人可以解释一下吗?

4

2 回答 2

2

$?正在获取local命令的返回码。尝试将local命令和赋值语句分开:

local opt
opt=$(whiptail ...
于 2017-09-13T08:13:42.797 回答
0

我发现了这个很棒的工具来检查 bash 脚本中可能存在的错误......

$ shellcheck myscript

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

$ 
于 2017-12-29T11:48:36.923 回答