Why test does not work on the function parameter:
myFunc() { if [ -n $1 ]; then echo 'TRUE' return fi echo 'FALSE' } myFunc 123 # TRUE myFunc # TRUE In the second case, I expected to see FALSE .
if no value is assigned to the var variable, then the operator
[ -n $var ] will be equivalent to the operator
[ -n ] which always returns true ( 0 ) as a return code.
if it is required that in such a situation the return code is “false” (non-zero value), the variable reference must be enclosed in double quotes:
[ -n "$var" ] in fact, it is always better to do this, because if the var variable contains, for example, a space, then the execution of the statement will cause a program error:
$ var="xy" $ [ -n $var ]; echo $? bash: [: x: binary operator expected 2 and with quotes it will execute correctly:
$ unset var $ [ -n "$var" ]; echo $? 1 $ var= $ [ -n "$var" ]; echo $? 1 $ var=x $ [ -n "$var" ]; echo $? 0 $ var="xy" $ [ -n "$var" ]; echo $? 0 Because the -n operator operates on a string ; therefore, the parameter $1 must be enclosed in double quotes (with single quotes, it will not be calculated, that is, it will appear as it is):
myFunc() { if [ -n "$1" ]; then echo 'TRUE' return fi echo 'FALSE' } myFunc 123 # TRUE myFunc # FALSE Source: https://ru.stackoverflow.com/questions/590465/
All Articles