我是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
我是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:\n\n" ## 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
的http:// bobcopeland.com/blog/2012/10/goto-in-bash/ –
http://stackoverflow.com/questions/9639103/is-there-a-goto-statement-in-bash – woahguy
請勿使用shell這樣的目的。 –