我試圖做一個行:打擊「聚結」的功能
if [ -z "$foo" ]
then
source "$foo/subdir/yo.sh"
else
source "$bar/yo.sh"
fi
(注意子目錄只出現如果使用FOO)。最簡單的解決方案到目前爲止是:
source "${foo:-$bar}${foo:+/subdir}/yo.sh"
換句話說,取foo或酒吧,然後追加/subdir
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或酒吧,然後追加/subdir
foo是否存在。有沒有更好的方法來做到這一點?
試試這個:
$((printf $foo 2>/dev/null && printf '/subdir') || printf $bar)/yo.sh
的令人費解的種類雖然。
該解決方案的關鍵方面是找到一種方法來輸出$ foo的內容(如果有的話),同時根據$ foo中是否有內容來分支。沒有參數的printf是一個錯誤,$ foo沒有內容導致printf沒有參數。之後,其餘的很容易。
由於這個原因,第一個printf
需要printf,但如果您願意,其他人可以用echo -n
代替。
嘗試
amithere=$foo
if [ ! -z "$amithere" ]
then
amithere=$bar
fi
source "$amithere/yo.sh"
if [[ -d $foo ]]; then
dir="$foo/subdir"
else
dir="$bar"
fi
source "$dir/yo.sh"
後者似乎混淆了我。爲什麼你想要在一個簡單的測試中使用'if' ...'fi'進行構造更好的測試?只要它仍然可以理解,只要短小就可以。 – Benoit 2010-11-10 10:39:43
問題是兩個解決方案都重複代碼 - 應該有一些方法只提一次「source」,「foo」和「/yo.sh」。 – l0b0 2010-11-10 12:19:18
我能想到的唯一其他形式是'[-z「$ foo」] && source「$ foo/subdir/yo.sh」|| 「$ bar/yo.sh」'或者像'dest =「$ foo/subdir/yo.sh」真的很難看「;源$ {dest /#\/subdir/$ bar}「'。 – 2010-11-10 14:42:31