2012-05-04 18 views
4

使用shell變量(BASH)的最優雅的方式是什麼,該變量包含用於globbing(文件名完成)的字符,用於觸發某些不需要的替換?下面是示例:在變量替換之後防止出現globbing

for file in $(cat files); do 
    command1 < "$file" 
    echo "$file" 
done 

文件名包含像'['或']'的字符。我有兩種基本思路:

1)關閉經由集-f通配符:我需要它的地方,否則

2)逃避文件的文件名:BASH抱怨「找不到文件」管道進入標準輸入時

THX任何建議

編輯:唯一的答案缺少的是如何從包含用於通配符時,文件名是在一個shell變量「$文件」,E特殊字符名稱的文件讀取。 G。 command1 <「$ file」。

回答

1

改爲使用while read

cat files | while read file; do 
    command1 < "$file" 
    echo "$file" 
done 
+0

這是一個很好的提示,謝謝。它會阻止for循環的列表結構中的globbing。但是兩個執行線在變量替換之後仍然會觸發globbing。 – fungs

4

您可以關閉與set -f通配符,然後用set +f重新打開以後在腳本中。

+0

這可能會起作用,但如果您必須在循環的每個循環中禁用並啓用globbing功能,那麼IMO不會優雅。 – fungs

8

作爲替代set -fset +f之間切換,你也許可以只申請一個set -f到子shell,因爲父shell的環境不會受到受此可言:

(
set -f 
for file in $(cat files); do 
    command1 < "$file" 
    echo "$file" 
done 
) 


# or even 

sh -f -c ' 
    for file in $(cat files); do 
     command1 < "$file" 
     echo "$file" 
    done 
'