Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 循环(?)if语句_Bash_Shell_Unix - Fatal编程技术网

Bash 循环(?)if语句

Bash 循环(?)if语句,bash,shell,unix,Bash,Shell,Unix,我是shell脚本编写的新手,我想知道: #!/usr/local/bin/bash number=5 echo "Enter 'yes' to continue, 'no' to abort:" read choice if [ $choice = yes ]; then while [ $number -lt 10 ]; do echo "The script is now looping!" done elif [ $choi

我是shell脚本编写的新手,我想知道:

#!/usr/local/bin/bash
number=5
echo "Enter 'yes' to continue, 'no' to abort:"
read choice
if [ $choice = yes ]; then
        while [ $number -lt 10 ]; do
                echo "The script is now looping!"
        done
elif [ $choice = no ]; then
        echo "Loop aborted"
else
        echo "Please say 'yes' or 'no'"
        read choice
# What now?
fi
如果您没有指定“是”或“否”,我将如何进行if语句重新检查您的$choice(第13行)

多谢各位

  • 您可以将代码从“echo Enter…”一直放到外部的“while”循环中。while循环将循环直到$choice为“yes”或“no”。执行此操作时删除最后一个“else”子句(这将是多余的)

  • 另外,您需要在内部while循环中增加(或更改)$number。否则,它将无限运行


  • 您可以跟踪是否在名为
    invalid\u choice的变量中循环

    invalid_choice=true
    while $invalid_choice; do
        read choice
        if [ "$choice" = "yes" ]; then
            invalid_choice=false
            ...
        elif [ "$choice" = "no" ]; then
            invalid_choice=false
            ...
        else
            echo "Please say yes or no"
    done
    
    或者,如果需要经常这样做,可以将其概括为一个函数:

    function confirm() {
        local ACTION="$1"
        read -p "$ACTION (y/n)? " -n 1 -r -t 10 REPLY
        echo ""
        case "$REPLY" in
            y|Y ) return 0 ;;
            *   ) return 1 ;;
        esac
    }
    
    confirm "Do something dangerous" || exit