如何在Shell脚本中使用goto语句 [英] How to use goto statement in shell script

查看:3979
本文介绍了如何在Shell脚本中使用goto语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是shell脚本的初学者.我对如何使用goto语句一无所知.我正在使用以下代码.

I am beginner in shell script. I don't have any idea about how to use goto statement. I am using the following code.

start:
echo "Main Menu"
echo "1 for Copy"
echo "2 for exit"
read NUM
case $NUM in
"1")
echo "CopyNUM"
goto start:;
"2")         
echo "Haiiii";
goto start:
*)
echo "ssss";
esac

推荐答案

正如其他人所指出的,bash(或其他类似POSIX的外壳)中没有goto-其他更灵活的流控制构造采用地点.
man bash中查找标题Compound Commands.

As others have noted, there's no goto in bash (or other POSIX-like shells) - other, more flexible flow-control constructs take its place.
Look for heading Compound Commands in man bash.

对于您来说,select命令是正确的选择. 由于使用方法可能并不明显,因此您可以开始以下操作:

In your case, the select command is the right choice. Since how to use it may not be obvious, here's something to get you started:

#!/usr/bin/env bash

echo "Main Menu"

# Define the choices to present to the user, which will be
# presented line by line, prefixed by a sequential number
# (E.g., '1) copy', ...)
choices=( 'copy' 'exit' )

# Present the choices.
# The user chooses by entering the *number* before the desired choice.
select choice in "${choices[@]}"; do

  # If an invalid number was chosen, $choice will be empty.
  # Report an error and prompt again.
  [[ -n $choice ]] || { echo "Invalid choice." >&2; continue; }

  # Examine the choice.
  # Note that it is the choice string itself, not its number
  # that is reported in $choice.
  case $choice in
    copy)
      echo "Copying..."
      # Set flag here, or call function, ...
      ;;
    exit)
      echo "Exiting. "
      exit 0
  esac

  # Getting here means that a valid choice was made,
  # so break out of the select statement and continue below,
  # if desired.
  # Note that without an explicit break (or exit) statement, 
  # bash will continue to prompt.
  break

done

这篇关于如何在Shell脚本中使用goto语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆