问题
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