我编写了一个 shell 脚本,我想在其中包含通过按键退出程序的功能q。我可以这样做吗?
这是我目前拥有的:
#!/bin/ksh
echo "Press Q to exit \t\t:\c"
read input
if [[ $input = "q" ]] || [[ $input = "Q" ]]
then exit 1
else
echo "Invalid Input."
fi
答案1
使用while read input
,但由于我们想避免重复该echo -en "Press Q to exit \t\t: "
语句两次,所以我们最好改用while true
(a做一会儿变体):
xiaobai:tmp $ cat hello.sh
#!/bin/ksh
while true; do
echo -en "Press Q to exit \t\t: "
read input
if [[ $input = "q" ]] || [[ $input = "Q" ]]
then break
else
echo "Invalid Input."
fi
done
xiaobai:tmp $ ./hello.sh
Press Q to exit : apple
Invalid Input.
Press Q to exit : q
xiaobai:tmp $