Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash "coalesce" functionality

Tags:

bash

I'm trying to do the following on a single line:

if [ -z "$foo" ]
then
    source "$foo/subdir/yo.sh"
else
    source "$bar/yo.sh"
fi

(note the subdir only present if foo is used). The simplest solution so far is:

source "${foo:-$bar}${foo:+/subdir}/yo.sh"

In other words, take either foo or bar, then append /subdir if foo exists. Is there a more elegant way to do this?

like image 421
l0b0 Avatar asked Apr 18 '26 05:04

l0b0


1 Answers

Try this:

$((printf $foo 2>/dev/null && printf '/subdir') || printf $bar)/yo.sh

Kind of convoluted though.

The key aspect to this solution is finding a way to both output the contents of $foo, if any, and simultaneously branch based on whether something was in $foo. printf with no arguments is an error and $foo with no contents results in no arguments to printf. After that the rest is easy.

For this reason the first printf needs to be printf but the others could be replaced with echo -n if you prefer.

like image 178
sorpigal Avatar answered Apr 20 '26 18:04

sorpigal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!