bash - Difference between chaining `test` and using an `if` statement -
is there difference between:
[ -f $foo ] && do_something ...and:
if [ -f $foo ]; do_something fi i thought equivalent, [ alias test, exits 0 when condition passes. however, in script have written, i'm checking whether environment variables set and, if not, bail out. in case:
[ -z "${my_env1+x}" -a -z "${my_env2+x}" ] && fail "oh no!" ...always seems bail out; when $my_env1 , $my_env2 are set. however, if version works correctly:
if [ -z "${my_env1+x}" -a -z "${my_env2+x}" ]; fail "oh no!" fi ...where fail defined as:
fail() { >&2 echo "$@" exit 1 }
i cannot diagnose source of problem answering question in title, difference between first && second , if first; second; fi know.
if first evaluates true, there no difference.
if first evaluates false, result of entire expression first && second false. if shell has -e flag set, cause abort. version using if statement, on other hand, never produce result if first evaluates false shell continue happily if -e set.
therefore, write more verbose if first; second; fi if cannot afford failure status. can important, example, when writing makefiles or if make general habit run scripts -e.
Comments
Post a Comment