2017-08-17 69 views
0

這裏是單行我感興趣的(尤其是在可變out):指定操作數DIRNAME作爲一個bash變量內部回聲

find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done 

我需要管道之前呼應此一襯墊到其他程序,但它失敗:

echo "find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done" 

與以下消息:

dirname: missing operand 
Try `dirname --help' for more information. 
find ~ | head -3 | while read f; do out=; echo ; done 

所以我使用s英格爾和雙引號:

echo "find ~ | head -3 | while read f; do out=$(dirname "'${f}'"); echo "'${out}'"; done" 

返回沒有錯誤:

find ~ | head -3 | while read f; do out=.; echo ${out}; done 

$(dirname ${f})沒有呼應的是

任何想法如何做到這一點?

回答

1

防止取代中使用單引號或逃避$

echo 'find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done' 

echo "find ~ | head -3 | while read f; do out=\$(dirname \${f}); echo \${out}; done" 
0

使用一個變量來存儲指令,並且迴應變量:

cmd='find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done' 
echo $cmd 
+0

該變量是不必要的,但如果你打算使用它,你*必須*引用擴展。 – chepner

0

我不知道爲什麼你需要打印僅限echo。但如果你想這樣只有然後參考如下:

echo `find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done`