Bash "joint" functionality

I am trying to do the following in one line:

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

(note that subdir is only present if foo is used). The simplest solution:

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

In other words, take either foo or bar, and then add /subdirif foo exists. Is there a more elegant way to do this?

+3
source share
3 answers

Try the following:

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

Kind of minimized though.

A key aspect of this solution is to find a way to output the contents of $ foo, if any, and a simultaneous branch based on what something was in $ foo. printf without arguments is an error, and $ foo without content does not produce printf arguments. After that, everything else is easy.

printf printf, echo -n, .

+2
if [[ -d $foo ]]; then
    dir="$foo/subdir"
else
    dir="$bar"
fi
source "$dir/yo.sh"
0

amithere=$foo   
if [ ! -z "$amithere" ]   
then    
    amithere=$bar    
fi    
source "$amithere/yo.sh"
-1

Source: https://habr.com/ru/post/1774063/


All Articles