#!/ bin / bash读取如果然后返回读取

时间:2016-08-02 11:43:33

标签: bash if-statement return

我想创建一个脚本,在你输入第一个命令之后,我希望被发送回上一个。

#!/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之后键入。它可以在同一个脚本中完成吗?

4 个答案:

答案 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)

在循环中包裹您想要重复的部分,并考虑如何从循环中退出。如果输入breakq命令将退出循环。否则,在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)

而且案例: #!/斌/庆典 虽然如此 做     读-p"请输入[x; y; z]:"命令     case $ COMMAND in         x)回声"这是命令x。 "             ;;         y)回声"这是命令y。 "             ;;         z)回声"这是命令z。 "             ;;         *)退出0             ;;     ESAC DONE 在行动: $ bash test.sh  请输入[x; y; z]:x  这是命令x。  请输入[x; y; z]:你  这是命令y。  请输入[x; y; Z Z  这是命令z。  请输入[x; y; z]:a $