Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent globbing after variable substitution

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".

like image 824
fungs Avatar asked May 04 '12 15:05

fungs


1 Answers

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
'
like image 111
tilo Avatar answered Sep 27 '22 19:09

tilo