The if
-statement performs a test that involves testing the shell variable DISABLE_CUSTOM_CREDS
twice. The first time the variable is used, it tests whether the variable's values is non-empty. If it is, it tests whether the non-empty value is numerically equal to zero.
Another way to write the code is as follows
if [[ -z "${ENABLE_CREDS}" && -n "${DISABLE_CUSTOM_CREDS}" && "${DISABLE_CUSTOM_CREDS}" -eq 0 ]]; then
ENABLE_CREDS=1
elif [[ -z "${ENABLE_CREDS}" && "${DISABLE_CUSTOM_CREDS}" -eq 1 ]]; then
ENABLE_CREDS=0
fi
export ENABLE_CREDS
Note the inserted -n
test operator, which tests for a non-empty string. This operator is implicit when you test on just a string.
It is unclear whether this initial test on DISABLE_CUSTOM_CREDS
being non-empty is needed (we don't see the rest of the code). It could be needed if the variable has a chance of being empty, in which case the test with zero would be true (and it's possible that the programmer didn't want this to trigger setting ENABLE_CREDS
to 1
).
This means that
- for
ENABLE_CREDS
to be set to 1
, ENABLE_CREDS
needs to be either unset or an empty string, DISABLE_CUSTOM_CREDS
must be non-empty and numerically equal to zero,
- for
ENABLE_CREDS
to be set to 0
, ENABLE_CREDS
must be unset or empty, and DISABLE_CUSTOM_CREDS
must be numerically equal to 1.
Without knowing more of the context of this code, I might venture to guess that the purpose of the if
statement as a whole is to set ENABLE_CREDS
to either 0
or 1
if it's not already set to some value, depending on the logical inverse of the variable DISABLE_CUSTOM_CREDS
.
if [ -z "$ENABLE_CREDS" ]; then
if [ "${DISABLE_CUSTOM_CREDS:-0}" = 1 ]; then
ENABLE_CREDS=0
else
ENABLE_CREDS=1
fi
fi
If ENABLE_CREDS
is empty, this tests DISABLE_CUSTOM_CREDS
(or the string 0
, if the variable is unset or empty) against 1
, and sets ENABLE_CREDS
to 0
or 1
depending on the outcome of that test.
The difference here is that this code always leaves ENABLE_CRED
with some value. It will either have its old non-empty value, or it is guaranteed to have the value 0
or 1
.
This is in contrast to the code in the question, which may leave the value of the variable empty if DISABLE_CUSTOM_CREDS
is empty or if it's some value like 2
(or indeed if it is the name of some other variable whose value is not 0 or 1; arithmetic evaluation is tricky, which is partly why I opted for a string comparison in the code above).