Is there an inline-if with assignment (ternary conditional) in bash?
Solution 1
There is no ?:
conditional operator in the shell, but you could make the code a little less redundant like this:
if [ $useDefault ]; then
tmpname="$defaultName"
else
tmpname="$customName"
fi
fileName="$dirName/$tmpname.txt"
Or you could write your own shell function that acts like the ?:
operator:
cond() {
if [ "$1" ] ; then
echo "$2"
else
echo "$3"
fi
}
fileName="$dirname/$(cond "$useDefault" "$defaultName" "$customName").txt"
though that's probably overkill (and it evaluates all three arguments).
Thanks to Gordon Davisson for pointing out in comments that quotes nest within $(...)
.
Solution 2
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
.
IQAndreas
SOreadytohelp Developer with multiple languages under my belt; primarily ActionScript 3, but also includes PHP, Java, and JavaScript. Just to be clear, I hate JavaScript: it's weakly typed, and its inheritance system is a joke. PHP isn't big on my list either. Yet, since the web uses them, I'm forced to work in them. IQAndreas.com - Main Website blog.iqandreas.com - Programming Blog GitHub.com/IQAndreas - GitHub Account and Repositories @IQAndreas - Twitter
Updated on July 27, 2022Comments
-
IQAndreas over 1 year
Possible Duplicate:
Ternary operator (?:) in BashIf 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?