fun*_*ngs 5 bash shell glob escaping
使用shell变量(BASH)的最优雅方法是什么,它包含为globbing(文件名完成)保留的字符,触发一些不需要的替换?这是一个例子:
for file in $(cat files); do
command1 < "$file"
echo "$file"
done
Run Code Online (Sandbox Code Playgroud)
文件名包含"['或']'等字符.我基本上有两个想法:
1)通过set -f关闭globbing:我需要它在其他地方
2)转义文件中的文件名:BASH在管道输入stdin时抱怨"找不到文件"
感谢任何建议
编辑:唯一的答案是如何从文件中读取包含用于globbing的特殊字符的文件,当文件名在shell变量"$ file"中时,例如command1 <"$ file".
小智 9
作为切换的替代方法set -f,set +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
'
Run Code Online (Sandbox Code Playgroud)
while read代替使用。
cat files | while read file; do
command1 < "$file"
echo "$file"
done
Run Code Online (Sandbox Code Playgroud)