我不正在寻找一种不同的方式来实现明显的意图。我希望理解为什么完全语法不起作用。
[root@lvs ~]# while true;do
> echo "Would you like the script to check the second box ([y]n)?"
> read ans
> if [ "$ans" == "n" ];then
> echo
> echo "bye"
> exit
> elif [ "$ans" != "" -o "$ans" != "y" ];then
> echo "Invalid entry..."
> else
> break
> fi
> done
Would you like the script to check the second box ([y]n)? **"Should have continued"**
Invalid entry...
Would you like the script to check the second box ([y]n)? **"Should have continued"**
y
Invalid entry...
Would you like the script to check the second box ([y]n)? **"Correct behavior"**
alskjfasldasdjf
Invalid entry...
Would you like the script to check the second box ([y]n)? **"Correct behavior"**
n
bye
这是一个与我发现的其他许多人相同的参考文献。我了解它正在做什么,当我读过的所有内容都说它应该使用逻辑bool时,它使用非逻辑的AND和OR。
http://www.groupsrv.com/linux/about140851.html
好的,就是这样,Nahuel的建议表明我最初的预期:
[root@lvs ~]# while true;do
> echo "Would you like the script to check the second box ([y]n)?"
> read ans
> if [ "$ans" = "n" ];then
> echo
> echo "bye!"
> exit
> elif [ "$ans" != "" -a "$ans" != "y" ];then
> echo "Invalid entry..."
> else
> break
> fi
> done
Would you like the script to check the second box ([y]n)?
asdfad
Invalid entry...
Would you like the script to check the second box ([y]n)?
[root@lvs ~]# while true;do
> echo "Would you like the script to check the second box ([y]n)?"
> read ans
> if [ "$ans" = "n" ];then
> echo
> echo "bye!"
> exit
> elif [ "$ans" != "" -a "$ans" != "y" ];then
> echo "Invalid entry..."
> else
> break
> fi
> done
Would you like the script to check the second box ([y]n)?
y
[root@lvs ~]# while true;do
> echo "Would you like the script to check the second box ([y]n)?"
> read ans
> if [ "$ans" = "n" ];then
> echo
> echo "bye!"
> exit
> elif [ "$ans" != "" -a "$ans" != "y" ];then
> echo "Invalid entry..."
> else
> break
> fi
> done
Would you like the script to check the second box ([y]n)?
n
logout
答案 0 :(得分:1)
问题是:[“$ ans”!=“” - o“$ ans”!=“y”]因为或否定而总是正确的。 $ ans不能等于“”和“y”。
尝试替换这些行
if [ "$ans" == "n" ];then
elif [ "$ans" != "" -o "$ans" != "y" ];then
通过这些
if [ "$ans" = "n" ];then
elif [ "$ans" != "" -a "$ans" != "y" ];then
或这些
if [[ $ans == n ]];then
elif [[ $ans != "" && $ans != y ]];then
更容易做的是一个案例:
case $ans in
y) echo "yes"
;;
n) echo "no"
;;
*)
;;
esac
break
也必须仅在for
或while
循环中使用,或在select
中使用,但您的帖子中缺少它。
答案 1 :(得分:0)
我真的不明白,你为什么在elif中使用-o。我会用“||”或“或”运算符。在if中使用两个条件时,应使用double [[and]]。 所以如果你使用:
elif [[ "$ans" != "" || "$ans" != "y" ]];then
它工作正常。
答案 2 :(得分:0)
确保输入的最合理方式是100%
if [ "$ans" == "n" ];then
echo
echo "bye"
exit
elif [ "$ans" == "y" ];then
echo Yes
break;
else
echo "Invalid entry... >$ans<"
fi