Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

macos - Return to previous commands in bash script?

I'm trying to implement a prev option in my bash script to go back to the previous "menu", as well as a way for the script to ask for user input again if no variable is set for $name.

Heres my bash script:

#!/bin/bash
#Menu() {
  for (( ; ; ))
  do
  beginORload=
  echo "Choose option:"
  echo "1 - Begin"
  echo "2 - Load"
  read -p "?" beginORload
#}
#Begin() {
if [ "$beginORload" -eq "1" ]
  then
  clear
  for (( ; ; ))
  do
  echo "Beginning. What is your name?"
  read -p "?" name
  #If "prev" specified, go back to #Menu()
  if [ "$name" -eq "prev" ]
    then
    Menu
  fi
  #If nothing specified, return to name input
  if [ -z ${name+x} ]
    then
    Begin
    else
    break
  fi
  echo "Hi $name !"
  done
fi
done

In batch, I could simply do:

:menu
echo Choose option:
echo 1 - Begin
echo 2 - Load
[...]
:begin
[...]
if "%name%==prev" goto menu
if "%name%==" goto begin

the issue is I keep running into errors all over the place, and I can't figure out what to type to get it to work

im running Yosemite btw. Thankyou

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this is close to what you expect:

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 
       ;;
    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!"

As a general idea you can wrap up your case selection in a while loop which will break under certain circumstances (i.e If Option 3 is selected or if a valid name is given (not blank - not prev)

PS1: In bash you compare integers with -eq , -ne, etc but you compare strings with == or !=

PS2: Check the above code online here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...