Search code examples
bashwhiptail

local variable changes whiptail behaviour


I have this script:

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

When I press ESC button, the output is as expected:

rc=255 opt=
ESC

Now, by making opt a local variable, the behaviour is different:

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

Output:

rc=0 opt=
This is an invalid choice

Can someone explain this?


Solution

  • $? is getting the return code of the local command. Try making the local command and the assignment separate statements:

    local opt
    opt=$(whiptail ...