Nested case in bash script

2019-08-26 08:06发布

问题:

I have written the following function in a bash script but it is not working. Am I missing something obvious?

main_menu() {
dialog \
    --title "Sim Gateway Infomation Utility" \
    --menu "What do you want to do?" 12 60 5 \
    Summary "View overall summary" \
    Details "View details of a sim bank" \
    Modify "Modify used minutes of a sim" \
    Exit "Exit" \
    2>$tempfile

retval=$?
case retval in
    0)

        choice=`cat $tempfile`
        case $choice in
            Summary) summary;;
            Details) details;;
            Modify) modify;;
            Exit) clean_up;;
        esac
        ;;
    1)
        confirm_exit;;
    255)
        confirm_exit;;
esac

}

回答1:

This article discusses dialog; I'm not experienced with it.

Your 'case retval in' needs to be 'case $retval in (or 'case "$retval" in).

[@Idelic notes that my original answer was more conservative than necesssary.]

The string 'retval' matches none of the options you list in your outer case statement (use a '*' option to detect the unexpected). The double quotes prevent accidents if $retval ever contained spaces; in general, it is a good idea to use double quotes around the variable in case "$var" in statements (and most other places too). In this particular case, it would not matter; the exit status is always a number. In the 'case "$choice" in' statement, I'd be more comfortable with the quotes around the variable - but you may still be safe (I'd need to read more about dialog to be sure of what it does and whether it ever generates spaces - or nothing even).