CONFIRM=""
echo "Do you want to backup your home directory? Please enter y|Y or n|N"
read CONFIRM;
if [[ "$CONFIRM" != "Y" ]] || [[ "$CONFIRM" != "y" ]]; then
echo "The backup will not run. Aborting now..."
else
echo "The backup will run now. Backing up to $DEST"
# more code
fi
每当我输入“y”或“Y”时,应执行else
下的条件。相反,无论我输入什么,if
下的条件都会被执行。我尝试了多种方括号和引用的组合,但是没有任何效果。为什么else
分支没有正确执行?
答案 0 :(得分:3)
此:
[[ "$CONFIRM" != "Y" ]] || [[ "$CONFIRM" != "y" ]]
表示" $CONFIRM
不是Y
或 $CONFIRM
不是y
" 。这总是保证是真的:
$CONFIRM
是Y
,那么它不是y
,所以第二个选项是真的$CONFIRM
为y
,那么它不是Y
,因此第一个选项为true $CONFIRM
是其他任何内容,那么两个选项都是真的要解决此问题,您需要使用&&
("和")代替||
("或"):
[[ "$CONFIRM" != Y ]] && [[ "$CONFIRM" != y ]]
,De Morgan's laws,相当于:
! { [[ "$CONFIRM" = Y ]] || [[ "$CONFIRM" = y ]] ; }
答案 1 :(得分:1)
如果我们仔细查看提示"请输入 y | Y或n | N " ,然后缺少第三种情况,处理无效输入。与@cdarke的答案一起,这会导致例如在以下短期条件下:
CONFIRM=""
echo "Do you want to backup your home directory? Please enter y|Y or n|N"
read CONFIRM;
if [[ "$CONFIRM" = [Yy] ]]; then
echo "The backup will run now. Backing up to $DEST"
# more code
elif [[ "$CONFIRM" = [Nn] ]]; then
echo "The backup will not run. Aborting now..."
else
echo "Wrong Input. Please enter y|Y or n|N."
fi
答案 2 :(得分:0)
另一个例子,我确保在特定y / n / q作为输入之前我们不会继续。使用-p -n1无需按Enter键。总结:一个case语句,读取一个按键,小写检查等...这个例子允许是/否或退出。
typeset confirm=''
while true; do
read -p "Select (y/n/q) ?" -n1 confirm
case ${confirm,,} in
y|n|q) break;;
*) echo "Answer y for yes / n for no or q for quit.";;
esac
done
echo -e "\nAnswer = $confirm" ;sleep 2
if [[ "${confirm,,}" == "q" ]] ; then
echo "OK Quitting.."
exit 0
fi
if [[ "${confirm,,}" == "y" ]] ; then
echo "Continuing ..."
else
echo "No? Do something else etc.. "
fi