局部变量改变了鞭尾行为

问题描述 投票:1回答:2

我有这个脚本:

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

有人可以解释一下吗?

bash whiptail
2个回答
2
投票

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

local opt
opt=$(whiptail ...

0
投票

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

$ shellcheck myscript

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

$ 
© www.soinside.com 2019 - 2024. All rights reserved.