我想创建一个脚本,在你输入第一个命令之后,我希望被发送回上一个。
#!/bin/bash
read -p " Please enter [x ; y ; z]: " COMMAND
if [ "$COMMAND" = x ] ; then
echo " This is command X. "
#Then return to read -p " Please enter [x ; y ; z]: " COMMAND
elif [ "$COMMAND" = y ]; then
echo " This is command y. "
#Then return to read -p " Please enter [x ; y ; z]: " COMMAND
elif [ "$COMMAND" = z ]; then
echo " This is command z"
#Then return to read -p " Please enter [x ; y ; z]: " COMMAND
else
echo " Command not found! "
fi
例如,如果键入x,我希望可以在y或z之后键入。它可以在同一个脚本中完成吗?
答案 0 :(得分:0)
递归函数可以轻松完成工作
#!/bin/bash
readfun(){
read -p " Please enter [x ; y ; z]: " command # Use lowercase names
[[ "$command" =~ ^[xyz]$ ]] && readfun
# logical AND ie '&&' terminates the recursion if any character other than x y z is entered
}
readfun #starting point for the script
echo "Command : ${command} not found"
答案 1 :(得分:0)
将整个事物包装在一个永无止境的while
循环中:
while true
do
[whatever]
done
答案 2 :(得分:0)
在循环中包裹您想要重复的部分,并考虑如何从循环中退出。如果输入break
,q
命令将退出循环。否则,在if
语句完成后,您将返回循环的顶部进行另一轮。
while true; do
read -p " Please enter [x ; y ; z; q]: " COMMAND
if [ "$COMMAND" = x ] ; then
echo " This is command X. "
elif [ "$COMMAND" = y ]; then
echo " This is command y. "
elif [ "$COMMAND" = z ]; then
echo " This is command z"
elif [ "$COMMAND" = q ]; then
break
else
echo " Command not found! "
fi
done
您可以使用case
语句而不是大if
语句来清除它。您可以为每个选项执行多个命令; ;;
表示每个特定块的结束。
while true; do
read -p " Please enter [x ; y ; z; q]: " COMMAND
case $COMMAND in
x) echo "This is command X."
;;
y) echo "This is command Y."
;;
z) echo "This is command Z."
;;
q) break ;;
esac
done
您还可以包含一个特定的测试来代替true
命令,以便循环本身可以检查命令的值并终止,而不是等待显式的break
命令。
while [ "$COMMAND" -ne q ]; do
read -p " Please enter [x ; y ; z; q]: " COMMAND
case $COMMAND in
x) echo "This is command X."
;;
y) echo "This is command Y."
;;
z) echo "This is command Z."
;;
esac
done
答案 3 :(得分:0)