局部变量改变了鞭打行为



我有这个脚本:

#!/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命令的返回代码。尝试制作local命令和分配单独的语句:

local opt
opt=$(whiptail ...

我找到了这个很棒的工具来检查可能的错误...

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

相关内容

  • 没有找到相关文章

最新更新