Prevent globbing after variable substitution

自闭症网瘾萝莉.ら 提交于 2020-01-22 21:29:46

问题


What is the most elegant way to use shell variable (BASH) that contain characters reserved for globbing (filename completion) that trigger some unwanted substitutions? Here is the example:

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

The file names contain characters like '[' or ']'. I have basically two ideas:

1) Turn off globbing via set -f: I need it somewhere else

2) Escape the file names in files: BASH complains about "file not found" when piping into stdin

Thx for any suggestion

Edit: The only answer missing is how to read from a file with name containing special characters used for globbing when the filename is in a shell variable "$file", e. g. command1 < "$file".


回答1:


As an alternative to switching between set -f and set +f you could perhaps just apply a single set -f to a subshell since the environment of the parent shell would not by affected by this at all:

(
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
'



回答2:


You can turn off globbing with set -f, then turn it back on later in the script with set +f.




回答3:


Use while read instead.

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


来源:https://stackoverflow.com/questions/10452107/prevent-globbing-after-variable-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!