Assigning the result of ‘test’ to a variable

As others have documented here, using the string “true” is a red herring; this is not an appropriate way to store boolean values in shell scripts, as evaluating it means dynamically invoking a command rather than simply inspecting the stored value using shell builtins hardcoded in your script.

Instead, if you really must store an exit status, do so as a numeric value:

[ -f "$file" ]               # run the test
result=$?                    # store the result

if (( result == 0 )); then   # 0 is success
  echo "success"
else                         # nonzero is failure
  echo "failure"
fi

If compatibility with set -e is desired, replace the first two lines of the above with:

result=0
[ -f "$file" ] || result=$?

…as putting the test on the left-hand side of || marks it as “checked”, suppressing errexit behavior. (That said, see BashFAQ #105 describing the extent to which set -e harms predictable, portable behavior; I strongly advise against its use).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)