I have discovered some strange behavior when using set -e
. A simple code: [ ${var} } && echo "text"
works fine outside a function but causes the script to exit when the same code is in a function. This only occurs if var=""
.
The code also works fine if I use ||
or if I set the var to something. Has anybody got an explanation for this?
#!/bin/bash
#version 4.4.20(1)
#set -x
set -e
var=
[ ${var} ] && echo "Test before function"
echo "Before function"
function test {
[ ${var} ] && echo "Test inside function"
}
test
echo end
Consider the following:
false && true
exits with exit status false
.
The default return value of a function is the return value of the last thing it ran.
set -e
is defined to cause early termination if any unchecked command ("unchecked" being a word which, in this context, has a complex, caveat-filled, version-dependent, nonportable, and otherwise often-surprising definition) returns an exit status other than true.
Thus, when you have a function that runs a-false-thing && a-true-thing
as its last command before returning, the function itself will return false, and set -e
will terminate execution if it considers the function's invocation "checked".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.