Possible Duplicate:
Ternary operator (?:) in Bash
If this were AS3 or Java, I would do the following:
fileName = dirName + "/" + (useDefault ? defaultName : customName) + ".txt";
But in shell, that seems needlessly complicated, requiring several lines of code, as well as quite a bit of repeated code.
if [ $useDefault ]; then
fileName="$dirName/$defaultName.txt"
else
fileName="$dirName/$customName.txt"
fi
You could compress that all into one line, but that sacrifices clarity immensely.
Is there any better way of writing an inline if with variable assignment in shell?
There is no
?:conditional operator in the shell, but you could make the code a little less redundant like this:Or you could write your own shell function that acts like the
?:operator:though that’s probably overkill (and it evaluates all three arguments).
Thanks to Gordon Davisson for pointing out in comments that quotes nest within
$(...).