我试图将存储在变量中的字符串与三个不同的字符串进行比较,如果它们都不匹配,则抛出错误。我尝试使用逻辑运算符 OR 在单个 if 语句中执行此操作。但是每次我都会收到错误,即使变量中存储的值与可能值之一相同。请找到我尝试过的片段。
if [[ "$TYPE" != "LOCAL" || "$TYPE" != "REMOTE" || "$TYPE" != "BOTH" ]]; then
echo -e "\n\tINCORRECT OR NULL ARGUMENTS PASSED. PLEASE VERIFY AND CORRECT THE USAGE MENTIONED AS BELOW: \n"
Usage
exit 1
fi
if [[ "$TYPE" != "LOCAL" ]] || [["$TYPE" != "REMOTE" ]] || [["$TYPE" != "BOTH" ]]; then
echo -e "\n\tINCORRECT OR NULL ARGUMENTS PASSED. PLEASE VERIFY AND CORRECT THE USAGE MENTIONED AS BELOW: \n"
Usage
exit 1
fi
答案1
你的逻辑已经落后了。任何字符串都保证不同于LOCAL
或者不同于REMOTE
因为字符串不能同时是LOCAL
和。REMOTE
在这里,执行该任务的正确工具是一条case
语句(这是sh
与那些[[...]]
ksh 运算符相反的标准语法):
case $TYPE in
(REMOTE|LOCAL|BOTH) ;; # OK
(*) printf >&2 'Error...\n'; exit 1;;
esac
如果您想在仿真中使用[[
,ksh
或bash
或 ,您可以这样做:zsh
ksh
if [[ $TYPE != @(REMOTE|LOCAL|BOTH) ]]; then
printf >&2 'Error...\n'
exit 1
fi
或[[ $TYPE != REMOTE && $TYPE != LOCAL && $TYPE != BOTH ]]
或[[ ! ($TYPE = REMOTE || $TYPE = LOCAL || $TYPE = BOTH) ]]
等等。
或者使用标准[
命令:[ "$TYPE" != REMOTE ] && [ "$TYPE" != LOCAL ] && [ "$TYPE" != BOTH ]
.
对于ksh93
,bash
或zsh
,另一种选择是使用关联数组:
typeset -A allowed_TYPE
allowed_TYPE=([REMOTE]=1 [LOCAL]=1 [BOTH]=1)
if ((!allowed_TYPE[\$TYPE])); then
printf >&2 'Error...\n'
exit 1
fi
通过 zsh
,您还可以使用普通数组:
allowed_TYPE=(REMOTE LOCAL BOTH)
if ((! $allowed_TYPE[(Ie)$TYPE]))...