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?
Just write:
fileName=${customName:-$defaultName}.txt
It's not quite the same as what you have, since it does not check useDefault
. Instead, it just checks if customName
is set. Instead of setting useDefault
when you want to use the default, you simply unset customName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With