我如何添加命令以将任何值放在参数上以回显无效输入
how can i add a command to put any value on an argument to echo invalid input
我必须保留“是”和“别无选择”,但我想输入一些内容,如果我不输入“是”或“否”以表明这是不可能的,我是新手,不知道该怎么做
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 ;;
您在这里走在正确的轨道上,但是最后的条件检查导致了问题。
您正在检查最后一个块中是否 "$input" == *
。当你像这样单独使用 *
时,你会得到一些古怪的行为。 shell 尝试将其扩展到当前目录中的所有文件。这意味着您可能会为条件提供太多参数,并且当当前目录中有多个文件时应该会收到类似于 [: too many argument
的错误。如果目录除了给定的脚本之外是空的,条件将扩展为 elif [ "$input" == some_file.txt]
并且脚本将继续并正常退出而没有所需的输出。请参阅 bash pattern matching and command expansion 文档。
此处最简单的解决方案是改用 else
。如果不满足前两个条件,则此块将执行,因此 $inputs
不是 yes 或 no。请参阅 bash conditional 文档。您的脚本应如下所示:
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
作为最后的评论,您可以利用 -p
参数将 read
命令简化为 1 行,来自用法:
-p prompt output the string PROMPT without a trailing newline before attempting to read
所以你可以把你的阅读压缩成read -p 'Do you wish to Exit? (yes/no)' input
我必须保留“是”和“别无选择”,但我想输入一些内容,如果我不输入“是”或“否”以表明这是不可能的,我是新手,不知道该怎么做
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 ;;
您在这里走在正确的轨道上,但是最后的条件检查导致了问题。
您正在检查最后一个块中是否 "$input" == *
。当你像这样单独使用 *
时,你会得到一些古怪的行为。 shell 尝试将其扩展到当前目录中的所有文件。这意味着您可能会为条件提供太多参数,并且当当前目录中有多个文件时应该会收到类似于 [: too many argument
的错误。如果目录除了给定的脚本之外是空的,条件将扩展为 elif [ "$input" == some_file.txt]
并且脚本将继续并正常退出而没有所需的输出。请参阅 bash pattern matching and command expansion 文档。
此处最简单的解决方案是改用 else
。如果不满足前两个条件,则此块将执行,因此 $inputs
不是 yes 或 no。请参阅 bash conditional 文档。您的脚本应如下所示:
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
作为最后的评论,您可以利用 -p
参数将 read
命令简化为 1 行,来自用法:
-p prompt output the string PROMPT without a trailing newline before attempting to read
所以你可以把你的阅读压缩成read -p 'Do you wish to Exit? (yes/no)' input