如果用户输入与给定的选项不匹配,如何提供错误消息?



我有一个脚本,看起来像这样:

until [[ "${answer}" = "exit" ]]
do
if [[ "${answer}" = "<option a>" ]]
then
<input some text>
fi
if [[ "${answer}" = "<option b>" ]]
then
<input some other text>
fi
done

我的问题是,如果用户键入任何与给定选项不匹配的内容,我想提供错误消息,并且我可以让它这样做,但是当用户在触发条件if/then语句之一后键入任何内容时,它仍然会提供错误消息。
我试着在我的until/do语句下做这样的事情。

if [ "${answer}" != "<option a>" ] || [ "${answer}" != "<option b>" ]
then
echo "Invalid input"

但是它仍然返回错误消息,因为在各种if/then语句中请求了输入。

有什么建议吗?

如果您只是想检查初始输入是否与您的任何选项不匹配,如:

#!/usr/bin/env bash
answer=$1
until [[ "$answer" == @(exit|option a|option b) ]]; do
printf >&2 'Invalid option %sn' "$answer"
exit 1
done
##: Process the rest of the script here.

如果不是这样,那么也许可以提供更多的信息。

相关内容