如何在shell脚本中使用goto语句



我是shell脚本的初学者。我对如何使用goto语句不了解。我正在使用以下代码。

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中没有goto(或其他类似Posix的外壳) - 其他,更灵活的流量控制构建体替代了它。
查找man bash中的Compound Commands标题。

在您的情况下,select命令是正确的选择。由于如何使用它可能并不明显,因此可以让您入门:

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

这是一个使用select循环来实现目标的简短示例。如果需要自定义格式,则可以使用自定义菜单的while循环,但是基本菜单是select旨在执行的操作:

#!/bin/bash
## array of menu entries
entries=( "for Copy"
          "for exit" )
## set prompt for select menu
PS3='Selection: '
while [ "$menu" != 1 ]; do                ## outer loop redraws menu each time
    printf "nMain Menu:nn"             ## heading for menu
    select choice in "${entries[@]}"; do  ## select displays choices in array
        case "$choice" in                 ## case responds to choice
            "for Copy" )
                echo "CopyNUM"
                break                     ## break returns control to outer loop
                ;;
            "for exit" )         
                echo "Haiiii, exiting"
                menu=1                    ## variable setting exit condition
                break
                ;;
            * )
                echo "ssss"
                break
                ;;
        esac
    done
done
exit 0

使用/输出

$ bash select_menu.sh
Main Menu:
1) for Copy
2) for exit
Selection: 1
CopyNUM
Main Menu:
1) for Copy
2) for exit
Selection: 3
ssss
Main Menu:
1) for Copy
2) for exit
Selection: 2
Haiiii, exiting

相关内容

  • 没有找到相关文章

最新更新