views:

173

answers:

1

Hi all,

I have written an if statement of the form:

if [ -n "${VAR:-x}" ]; then
   #do something
   export VAR=#something
fi

My shell script calls this statement twice and surprisingly passes the condition twice.

[hint (perhaps...): This exact code is repeated in a function in an included file. The if statement is first evaluated prior to function invocation. It is "again" evaluated when the function is invoked.]

What is the matter here? Do I understand the -x flag incorrectly?

Thanks!

+3  A: 

${VAR:-x} says if VAR is not set substitute the string x otherwise substitute the value of VAR.

Similarly, ${FOO:-bar} says substitute the value of FOO or the string bar if FOO is not set as described here.

This means -n "${VAR:-x}" will always be true as -n means check if not blank and "${VAR:-x}" will never be blank.

Dave Webb
How then do I query a variable's existence/not-nullness?
Yaneeve
Just -n "${VAR}" should do it. This will be true if VAR is set and not blank.
Dave Webb