||= (or equal operator) in bash?
If you’re used to writing code in ruby, perl, or other languages that provide an ||= (or equal) type operator, you may someday find yourself wanting to do the same in a shell script. While this isn’t directly provided in bash, for example (at least not that I could find), you can emulate the same functionality.
The answer lies in using a little bit of of tomfoolery from the Advanced Bash Scripting Guide, specifically under the Parameter Substitution section.
The part we’re interested in at this point is the ability to use a default parameter. These constructs in bash look like so:
${parameter-default}
and
${parameter:-default}
Note that as pointed out in the documentation, the difference between the two is that the former will not evaluate if parameter is null whereas the latter will.
So just how do we accomplish something like:
$foo ||= $bar ||= $baz
Like so:
FOO=${FOO:-$BAR}
FOO=${FOO:-$BAZ}
FOO=${FOO:-foo}
So this short circuits just like the ||= type operator above. So say, for example, you wanted to spit out a diff of some code before confirmation of a submit or something. Ideally you want to fire up the diff program the user prefers. So why not do something like:
DIFF=${DIFF:-$MYOTHERDIFF}
DIFF=${DIFF:-diff}
In this example, we use what is in $DIFF first. If there’s nothing in $DIFF, we use $MYOTHERDIFF. Finally, if there is nothing in either, we use straight up diff. This way if certain diff variables are set to programs like gvimdiff, tkdiff, etc., they will be invoked.