Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an inline-if with assignment (ternary conditional) in bash? [duplicate]

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?

like image 852
IQAndreas Avatar asked Dec 31 '12 23:12

IQAndreas


1 Answers

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.

like image 154
William Pursell Avatar answered Oct 06 '22 06:10

William Pursell