Bash – How to prevent word splitting without preventing empty string removal

bashnullparameter

I need to pass as a program argument a parameter expansion. The expansion results in a filename with spaces. Therefore, I double-quote it to have the filename as a single word: "$var".

As long as $var contains a filename, the program gets a single-word argument and it works fine. However, at times the expansion results in an empty string, which when passed as argument, breaks the program (which I cannot change).

Not removing the empty string is the specified behavior, according to Bash Reference Manual:

If a parameter with no value is expanded within double quotes, a null argument results and is retained.

But then, how do I manage the case where I need to quote variables, but also need to discard an empty string expansion?

EDIT:

Thanks to George Vasiliou, I see that a detail is missing in my question (just tried to keep it short 🙂 ). Running the program is a long java call, which abbreviated looks like this:

java -cp /etc/etc MyClass param1 param2 "$var" param4

Indeed, using an if statement like that described by George would solve the problem. But it would require one call with "$var" in the then clause and another without "$var" in the else clause.

To avoid the repetition, I wanted to see if there is a way to use a single call that discards the expansion of "$var" when it is empty.

Best Answer

The ${parameter:+word} parameter expansion form seems to do the job

( xyz=2; set -- ${xyz:+"$xyz"}; echo $# )
1

( xyz=; set -- ${xyz:+"$xyz"}; echo $# )
0

( unset xyz; set -- ${xyz:+"$xyz"}; echo $# )
0

So that should translate to

program ${var:+"$var"}

in your case

Related Question