在变量替换后防止通配符扩展。

5
什么是使用包含通配符(文件名补全)的shell变量(BASH)的最优雅方式,以避免触发一些不必要的替换?以下是示例:
for file in $(cat files); do
   command1 < "$file"
   echo "$file"
done

文件名包含像'['或']'这样的字符。我基本上有两个想法:
1)通过set -f关闭globbing:我需要在其他地方使用它。
2)在文件中转义文件名:当将内容管道传输到stdin时,BASH会抱怨“找不到文件”。
感谢任何建议。
编辑:唯一缺少的答案是如何读取包含用于globbing的特殊字符的名称的文件,当文件名在shell变量“$file”中时,例如command1 < "$file"。
3个回答

9
作为在使用 set -fset +f 之间切换的替代方案,你也许可以只在子shell中应用单个 set -f,因为父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
'

5

您可以使用set -f关闭 globbing,在脚本中稍后使用 set +f重新打开。


这可能有效,但如果您必须在每个循环周期中禁用和启用全局特性,那么在我看来并不优雅。 - fungs

2
请使用while read代替。
cat files | while read file; do
    command1 < "$file"
    echo "$file"
done

这是一个很好的提示,谢谢。它将防止在for循环的列表构造中进行globbing。但是,在变量替换后,这两行执行代码仍然会触发globbing。 - fungs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接