[英]how can i add a command to put any value on an argument to echo invalid input
i have to keep the yes and no choice but i want to put something that if i don't type yes or no to show that this is not possible i am new to this and not sure what to do我必须保留“是”和“否”的选择,但我想输入一些内容,如果我不输入“是”或“否”以表明这是不可能的,我对此并不陌生,不知道该怎么做
echo "Do you wish to Exit?(yes/no)"
read input
if [ "$input" == "yes" ]
then
clear
exit
elif [ "$input" == "no" ]
then
clear
echo "Reloaded"
echo -e "\n"
elif [ "$input" == * ]
then
echo "Invalid Input"
fi ;;
You are on the right track here, the last condition check is causing issues however.您在这里走在正确的轨道上,但是最后的条件检查会导致问题。
You are checking if "$input" == *
in the last block.您正在检查最后一个块中的
"$input" == *
是否。 When you use *
on its own like that you can get some wacky behavior.当你像这样单独使用
*
时,你会得到一些古怪的行为。 The shell tries to expand it to all the files in the current directory. shell 尝试将其展开到当前目录中的所有文件。 This means that you will likely be giving too many arguments to the conditional and should get an error similar to
[: too many argument
when there are several files in the current directory.这意味着您可能会为条件提供太多 arguments,并且当当前目录中有多个文件时,应该会收到类似于
[: too many argument
的错误。 If the directory is empty except for the given script the conditional will be expanded to elif [ "$input" == some_file.txt]
and the script will continue and exit normally without the desired output.如果目录为空,除了给定的脚本,条件将扩展为
elif [ "$input" == some_file.txt]
并且脚本将继续并正常退出而没有所需的 output。 See the bash pattern matching and command expansion documentation.请参阅 bash 模式匹配和命令扩展文档。
The simplest solution here is to use an else
instead.这里最简单的解决方案是使用
else
代替。 This block will execute if the first two conditions are not met, and therfore $inputs
is something other than yes or no.如果前两个条件不满足,则此块将执行,因此
$inputs
不是是或否。 See the bash conditional documentation.请参阅bash 条件文档。 You script should look something like this:
您的脚本应如下所示:
echo "Do you wish to Exit?(yes/no)"
read input
if [ "$input" == "yes" ]
then
clear
exit
elif [ "$input" == "no" ]
then
clear
echo "Reloaded"
echo -e "\n"
else
echo "Invalid Input"
fi
As a final comment, you can simplify the read
command into 1 line by leveraging the -p
argument, from the usage:作为最后的评论,您可以通过利用
-p
参数将read
命令简化为 1 行,来自用法:
-p prompt output the string PROMPT without a trailing newline before attempting to read
So you can condense your read into read -p 'Do you wish to Exit? (yes/no)' input
所以你可以将你的阅读浓缩成
read -p 'Do you wish to Exit? (yes/no)' input
read -p 'Do you wish to Exit? (yes/no)' input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.