可能的脚本:
# A script that checks if user input matches a certain value.
echo "What is the capital of France?"
read capital
if [ "$capital" == "Paris" ];
then
echo "Correct!"
else
echo "Wrong, try again."
read capital
if [ "$capital" == "Paris" ];
then
echo "Correct!"
else
echo "Wrong again."
fi
fi
这个脚本会提示用户输入一个答案,检查答案是否为“Paris”。如果不是,脚本会提示用户再试一次,直到用户正确回答为止。
然而,这个脚本存在一个问题。如果用户一开始输入的是“Paris ”(包含多余空格),那么该脚本会给出错误的输出。
为了避免这种问题,可以使用“-z”选项检查用户输入是否为空,并使用“tr -d”命令删除多余的空格。这是修改后的脚本:
# A script that checks if user input matches a certain value.
echo "What is the capital of France?"
read capital
trimmed=$(echo "$capital" | tr -d ' ')
if [ -z "$trimmed" ];
then
echo "You didn't enter anything."
elif [ "$trimmed" == "Paris" ];
then
echo "Correct!"
else
echo "Wrong, try again."
read capital
trimmed=$(echo "$capital" | tr -d ' ')
if [ -z "$trimmed" ];
then
echo "You didn't enter anything."
elif [ "$trimmed" == "Paris" ];
then
echo "Correct!"
else
echo "Wrong again."
fi
fi
这个修改后的脚本使用了“trimmed”变量来存储已删除多余空格的用户输入。在检查用户是否正确回答时,我们使用了“-z”选项来检查用户是否输入了空字符串,并且使用了“tr -d”命令删除了多余的空格。
上一篇:bash脚本问题[:参数过多