如果没有用户输入,请退出BASH脚本



我的bash脚本应该使用户输入以处理以下的特定文件:

if [ -e "formatted_log.csv" ]
then
    printf "nPresence of formatted_log.csv file detected: It appears this script has already been run is this dir.n"
    printf "Appending can cause errors.n"
    read -e -p "Would you like to continue?[y/n]" stdin

此逻辑检查用户的输入:

if [ $stdin = "n" ] || [ $stdin = "N" ];
then 
printf "nOkay, exiting.n"
exit;
fi
if [ $stdin != "y" ]&&[ $stdin != "Y" ]&&[ $stdin != "n" ]&&[ $stdin != "N" ]; 
then 
printf "nPlease use a valid input (y/n)...exiting.n"
exit;
    fi
fi

问题是,如果您只按Enter Enter脚本执行,就好像输入了" Y"或" Y",我不知道为什么。我的理解是,如果用户放入y,y,n或n。

当您没有输入时,它会打印出来:

master_script.sh: line 14: [: =: unary operator expected
master_script.sh: line 14: [: =: unary operator expected
master_script.sh: line 19: [: !=: unary operator expected

,但没有退出–我该如何退出?

由于您已经用" bash"标记了此标签,因此您应该拥有更强大的[[ ]]操作员。然后,您可以简化这样的东西:

read stdin
if [[ $stdin == [Nn] ]]; then
    echo "Exiting"
    exit
fi
if [[ $stdin != [YyNn] ]]; then
    echo "Invalid input, exiting"
    exit
fi

==(或 =)和 [[ ]]中的 != perform 模式匹配,因此您可以使用模式检查输入是否有效,在诸如[YyNn]之类的单个表达式中。

如果要要求输入,直到用户输入有效的内容,则可以这样循环:

while [[ $stdin != [YyNn] ]]; do
    read -p 'Continue? ' stdin
done

请注意,虽然在Bash中引用您的变量几乎总是很好的做法,但您不必在[[ ]]中。而且,如果您的模式在变量中,则实际上不得引用,或者不被解释为模式。

问题是不是在变量 $stdin周围的引号当不存在引用时,它不会以空价值保留,

例如, [...]看到变量为空时的表达式如下,

+ '[' = n ']'
script.sh: line 9: [: =: unary operator expected
+ '[' = N ']'
script.sh: line 9: [: =: unary operator expected
+ '[' '!=' y ']'
script.sh: line 14: [: !=: unary operator expected
+ '[' 0 eq 0 ']'

您需要正确引用它们,以使其在行中起作用

9 if [ "$stdin" = "n" ] || [ "$stdin" = "N" ];

14  if [ "$stdin" != "y" ] && [ "$stdin" != "Y" ] && [ "$stdin" != "n" ] && [ "$stdin" != "N" ];

这样,Enter键按安全处理为

+ '[' '' = n ']'
+ '[' '' = N ']'
+ '[' '' '!=' y ']'
+ '[' '' '!=' Y ']'
+ '[' '' '!=' n ']'
+ '[' '' '!=' N ']'

随着以上更改运行完整脚本,并按在调试模式下的提示符上按 Enter

 bash -x script.sh 
+ '[' -f file ']'
+ printf 'nPresence of formatted_log.csv file detected: It appears this script has already been run is this dir.n'
Presence of formatted_log.csv file detected: It appears this script has already been run is this dir.
+ printf 'Appending can cause errors.n'
Appending can cause errors.
+ read -e -p 'Would you like to continue?[y/n]' stdin
Would you like to continue?[y/n]
+ '[' '' = n ']'
+ '[' '' = N ']'
+ '[' '' '!=' y ']'
+ '[' '' '!=' Y ']'
+ '[' '' '!=' n ']'
+ '[' '' '!=' N ']'
+ printf 'nPlease use a valid input (y/n)...exiting.n'
Please use a valid input (y/n)...exiting.
+ exit

作为健康的替代方案,您可以在允许的提示列表中使用否定的正则匹配项,如下

if [[ ! $stdin =~ ^(y|Y|n|N)$ ]]

另一种有效的方法只需在变量上检查一个空字符串,

if [ "$stdin" = "" ]

相关内容

  • 没有找到相关文章

最新更新