-
Notifications
You must be signed in to change notification settings - Fork 1.9k
SC2055
Joachim Ansorg edited this page Nov 12, 2021
·
8 revisions
if [[ $1 != foo || $1 != bar ]]
then
echo "$1 is not foo or bar"
fiif [[ $1 != foo && $1 != bar ]]
then
echo "$1 is not foo or bar"
fiThis is not a bash issue, but a simple, common logical mistake applicable to all languages.
[[ $1 != foo || $1 != bar ]] is always true (when foo != bar):
- If
$1 = foothen$1 != baris true, so the statement is true. - If
$1 = barthen$1 != foois true, so the statement is true. - If
$1 = cowthen$1 != foois true, so the statement is true.
[[ $1 != foo && $1 != bar ]] matches when $1 is neither foo nor bar:
- If
$1 = foo, then$1 != foois false, so the statement is false. - If
$1 = bar, then$1 != baris false, so the statement is false. - If
$1 = cow, then both$1 != fooand$1 != baris true, so the statement is true.
This statement is identical to ! [[ $1 = foo || $1 = bar ]], which also works correctly.
Rare.
- If I want to check that $FOO, $BAR and $COW are all equal:
if [[ $FOO != $BAR || $FOO != $COW ]]
then
echo "$FOO and $BAR and $COW are not all equal"
fi