返回bash脚本中的上一个命令[PART 2 FOLLOWUP]

时间:2017-07-22 06:32:26

标签: bash

我之前在这里问了一个类似的问题:Return to previous commands in bash script?

我现在的不同之处在于,我收到的答案只是部分有效。我试图联系回答者,但我没有回复。

无论如何,我正在尝试添加更多菜单并拥有更多" prev"选项。例如,我想要:

while [[ $answer -ne '3' ]];do
echo "Choose option:"
echo "1 - Begin"
echo "2 - Load"
echo "3 - Exit"
read -p "Enter Answer [1-2-3]:" answer
    case "$answer" in
    1) while [[ "$nm" == '' ]];do read -p "What is your Name:" nm;done # Keep asking for a name if the name is empty == ''
    if [[ $nm == "prev" ]];then nm=""; else echo "Hello $nm" && break; fi  # break command breaks the while wrapper loop 

##Begin my custom code:

    read -p ""What is your favourite colour?" cr
    if [[ $cr == "prev" ]];then cr="" # And return to "What is your name"
    echo "$cr is my favourite, too!
# And keep going on and on, utilizing the "prev" command to go back to the previous question.

#End my custom code.

     ;;
    2) echo 'Load' ;;
    3) echo 'exiting...' ;;                                          # Number 3 causes while to quit.
    *) echo "invalid selection - try again";;                        # Selection out of 1-2-3 , menu reloaded
esac                                                                 # case closing 
done                                                                 # while closing
echo "Bye Bye!"

请理解我写这篇文章很困难。请放轻松我^^;

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你正在寻找这样的东西, 我提供了一些解释性意见。

begin() {
    # local variables that should not be visible outside this function
    local name color

    while :; do
        while [[ $name == '' ]]; do
            read -p "What is your Name:" name
        done

        if [[ $name == prev ]]; then
            # exit function, return to menu
            return
        fi
        echo "Hello $name"

        read -p "What is your favourite colour?" color
        if [[ $color == prev ]]; then
            # clear the current variable, and the previous too, to repeat previous question
            color=
            name=
            continue
        fi
        echo "$color is my favourite, too!"

        # all done here, return to menu
        return
    done
}

while [[ $answer -ne 3 ]]; do
    echo "Choose option:"
    echo "1 - Begin"
    echo "2 - Load"
    echo "3 - Exit"
    read -p "Enter Answer [1-2-3]:" answer
    case "$answer" in
        1) begin ;;
        2) echo 'Load' ;;
        3) echo 'exiting...' ;;
        *) echo "invalid selection - try again" ;;
    esac
done
echo "Bye Bye!"