我编写了一个 bash shell 脚本(代码如下),为用户提供了 4 个选项。但是我在编写代码时遇到了一点麻烦。现在,当他们选择选项 3 时,显示日期。它会一遍又一遍地循环。我必须关闭终端窗口才能停止它,因为它是一个无限循环。我该如何防止这种情况发生?另外,退出似乎也不起作用。
如果有人能帮助我一点,谢谢。
#!/bin/bashe
echo -n "Name please? "
read name
echo "Menu for $name
1. Display a long listing of the current directory
2. Display who is logged on the system
3. Display the current date and time
4. Quit "
read input
input1="1"
input2="2"
input3=$(date)
input4=$(exit)
while [ "$input" = "3" ]
do
echo "Current date and time: $input3"
done
while [ "$input" = "4" ]
do
echo "Goodbye $input4"
done
答案1
紧凑版本:
options=(
"Display a long listing of the current directory"
"Display who is logged on the system"
"Display the current date and time"
"Quit"
)
PS3="Enter a number (1-${#options[@]}): "
select option in "${options[@]}"; do
case "$REPLY" in
1) ls -l ;;
2) who ;;
3) date ;;
4) break ;;
esac
done
答案2
我猜这是由于while
循环所致;)
的值$input
在循环内不会改变。要么read input
在循环中插入类似的东西,要么将 更改为while ... do
。如果我正确理解了脚本的意图,你现在if ... then
不需要这些循环。你需要一个while
大的 while
循环覆盖从始至终echo "Menu for $name
的所有内容。
我的脚本版本如下:
#!/bin/bash
echo -n "Name please? "
read name
input=""
while [ "$input" != "4" ]; do
echo "Menu for $name
1. Display a long listing of the current directory
2. Display who is logged on the system
3. Display the current date and time
4. Quit "
read input
input1="1"
input2="2"
input3=$(date)
input4=$(exit)
if [ "$input" = "3" ]; then
echo "Current date and time: $input3"
fi
if [ "$input" = "4" ]; then
echo "Goodbye $input4"
fi
done
答案3
案例可以帮助您,尝试一下
# cat list.sh
#!/bin/bash
echo -n "Name please? "
read name
echo "Menu for $name"
echo -e "Enter ( 1 ) to Display a long listing of the current directory \nEnter ( 2 ) to Display who is logged on the system\nEnter ( 3 ) to Display the current date and time\nEnter ( 4 ) to Quit"
read en
case "$en" in
1)ls -lR;;
2)who;;
3)date;;
4)echo "Good Bye..."
sleep 0;;
*)echo "Wrong Option selected" ;;
esac
输出:
# ./list.sh
Name please? Ranjith
Menu for Ranjith
Enter ( 1 ) to Display a long listing of the current directory
Enter ( 2 ) to Display who is logged on the system
Enter ( 3 ) to Display the current date and time
Enter ( 4 ) to Quit
如果你输入其他选项,然后菜单显示,然后
# ./list.sh
Name please? Ranjith
Menu for Ranjith
Enter ( 1 ) to Display a long listing of the current directory
Enter ( 2 ) to Display who is logged on the system
Enter ( 3 ) to Display the current date and time
Enter ( 4 ) to Quit
5
Wrong Option selected
...