只要在bash中按“是”,如何执行“是/否”操作?

Joh*_*lor 2 scripting bash

假设我在 bash 脚本中有 Yes/No 结构:

read -r -p "Yes or no?" response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
 then 
 do ...
else
 exit 0
fi
Run Code Online (Sandbox Code Playgroud)

我希望这个构造一直执行到我按“否”为止。即,如果我按“是”,那么在操作完成后“做...”执行我想再次“是还是否?” 回复。

ter*_*don 6

你需要不断地要求回应,直到它不是你想要的:

while true;
do
    read -r -p "Yes or no? " response   
    if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
    then
        echo "You chose yes"
    else
        exit 0
    fi
done
Run Code Online (Sandbox Code Playgroud)