bash 脚本:如果多个 OR 条件未按预期工作

bash 脚本:如果多个 OR 条件未按预期工作

对于下面的脚本,如果我从“abc”用户运行,该脚本不应运行“exit 1”。仍然运行“exit 1”。

if [ "$(whoami)" != "abc" ] || [ "$(whoami)" != "xyz" ] || [ "$(whoami)" != "pqr" ]
then
    exit 1
else
    echo "Run remaining script"
fi

答案1

bash 脚本对我来说似乎工作正常。您正在运行,abc这意味着第一个测试为 false(abc等于abc),因此评估继续到下一个为 true(abc不等于xyz)的测试,并且脚本退出,因为您得到false || true || true的是true

如果您想“运行剩余脚本” ,如果用户是 、 、 之一abc,则应使用 OR 并反转和条件,或者保持相同并使用 AND。xyzpqr==ifelse

所以要么是这样的:

if [ "$(whoami)" != "abc" ] && [ "$(whoami)" != "xyz" ] && [ "$(whoami)" != "pqr" ]
then
    exit 1
else
    echo "Run remaining script"
fi

或者:

if [ "$(whoami)" == "abc" ] || [ "$(whoami)" == "xyz" ] || [ "$(whoami)" == "pqr" ]
then
    echo "Run remaining script"
else
    exit 1
fi

答案2

这串 if 的替代方案可以是:

case "$(whoami)" in
   abc|xyz|pqr)  : # we do nothing here, 
                 ;; # and exit the case
   *)            exit 1  # for all other values (*) : we exit 1, terminating the script
                 ;;
esac
# here, we only continue if the case before had abc, xyz or pqr
...

相关内容