我有一個bash shell腳本,可以遍歷某個目錄的所有子目錄(但不是文件)。問題是一些目錄名稱包含空格。如何逃避bash循環列表中的空白區域?
這裏是我的測試目錄的內容:
$ls -F test
Baltimore/ Cherry Hill/ Edison/ New York City/ Philadelphia/ cities.txt
並通過目錄循環代碼:
for f in `find test/* -type d`; do
echo $f
done
這裏的輸出:
test/Baltimore test/Cherry Hill test/Edison test/New York City test/Philadelphia
櫻桃山和紐約市被視爲2或3個單獨的條目。
我想引用的文件名,例如:
for f in `find test/* -type d | sed -e 's/^/\"/' | sed -e 's/$/\"/'`; do
echo $f
done
,但無濟於事。
有一個簡單的方法來做到這一點。
下面的答案很好。但是爲了使這更加複雜 - 我並不總是希望使用我的測試目錄中列出的目錄。有時我想將目錄名稱作爲命令行參數傳入。
我把設置IFS的查爾斯的建議,並與下面的上前:
dirlist="${@}"
(
[[ -z "$dirlist" ]] && dirlist=`find test -mindepth 1 -type d` && IFS=$'\n'
for d in $dirlist; do
echo $d
done
)
,除非有在命令行參數(即使這些參數均以)空間這個工作得很好。例如,調用這樣的腳本:test.sh "Cherry Hill" "New York City"
輸出如下:
Cherry Hill New York City
不知道有關-exec是 '+' 的味道。 sweet – 2008-11-19 05:27:33
tho看起來像它也可以,就像xargs一樣,只會將參數放在給定命令的末尾:/這有時會給我帶來麻煩 – 2008-11-19 05:35:21
我認爲-exec [name] {} +是一個GNU和4.4-BSD擴展。 (至少,它不會出現在Solaris 8上,我認爲它也不在AIX 4.3中。)我想我們其他人可能會被塞進xargs ... – 2008-11-19 06:00:51