Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash“;联合;功能_Bash - Fatal编程技术网

Bash“;联合;功能

Bash“;联合;功能,bash,Bash,我试图在一行上完成以下操作: if [ -z "$foo" ] then source "$foo/subdir/yo.sh" else source "$bar/yo.sh" fi (请注意,只有在使用foo时,才会出现子目录)。到目前为止,最简单的解决方案是: source "${foo:-$bar}${foo:+/subdir}/yo.sh" 换句话说,采用foo或bar,如果foo存在,则追加/subdir。有更优雅的方法吗?试试看 amithere=$foo

我试图在一行上完成以下操作:

if [ -z "$foo" ]
then
    source "$foo/subdir/yo.sh"
else
    source "$bar/yo.sh"
fi
(请注意,只有在使用foo时,才会出现子目录)。到目前为止,最简单的解决方案是:

source "${foo:-$bar}${foo:+/subdir}/yo.sh"
换句话说,采用foo或bar,如果foo存在,则追加
/subdir
。有更优雅的方法吗?

试试看

amithere=$foo   
if [ ! -z "$amithere" ]   
then    
    amithere=$bar    
fi    
source "$amithere/yo.sh"
试试这个:

$((printf $foo 2>/dev/null && printf '/subdir') || printf $bar)/yo.sh
不过有点复杂

此解决方案的关键方面是找到一种方法,既可以输出$foo的内容(如果有),也可以根据$foo中是否有内容同时进行分支。没有参数的printf是一个错误,没有内容的$foo导致printf没有参数。在那之后,剩下的就容易了


出于这个原因,第一个
printf
需要是printf,但是如果您愿意,其他的可以用
echo-n
替换。

后者对我来说似乎很模糊。当使用
if
进行结构良好的测试时,为什么要将它放在一行上<代码>fi可读性更好吗?只要仍然可以理解,简短是可以的问题是这两种解决方案都会重复代码-应该有某种方式只提到一次“source”、“foo”和“/yo.sh”。我能想到的其他形式只有
[-z“$foo”]&&source“$foo/subdir/yo.sh”|“$bar/yo.sh”
或者像
dest这样非常丑陋的东西=“$foo/subdir/yo.sh”source${dest/\/subdir/$bar}”
$((printf $foo 2>/dev/null && printf '/subdir') || printf $bar)/yo.sh