返回bash脚本中的上一个命令?

时间:2017-07-12 07:27:51

标签: bash macos shell

我正在尝试在我的bash脚本中实现prev选项以返回上一个“菜单”,以及如果没有设置变量,脚本再次请求用户输入的方法$name

继承我的bash脚本:

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

批次中,我可以这样做:

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

问题是我在整个地方都遇到了错误,我无法弄清楚要输入什么来使其工作

我正在运行Yosemite btw。三江源

1 个答案:

答案 0 :(得分:0)

这样的事情接近你的期望:

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

作为一般概念,您可以将case选项包含在while循环中,该循环在某些情况下会中断(即如果选择了选项3或者是否给出了有效名称(不是空白 - 不是上一个)< / p>

PS1:在bash中,您将整数与-eq-ne等进行比较,但您将字符串与==!=进行比较

PS2:检查上面的代码online here