I am writing a very simple script and I'm getting stuck on something stupid. Basically I have text file in which each line is comprised of 3 words separated by a space. When you cat the file it shows everything correctly. For example catting the file looks something like this:

bird dog mouse
ferret bunny hare

I'm doing a simple for loop like this:

for line in $(cat pets.txt)
     echo $line
     "command $line"

The echo is showing the problem. The command needs to run as

command bird dog mouse

and instead it is running as

command bird
command dog
command mouse

This seems like it should be a simple fix, but I can't get my search terms right to find the solution.



The issue is that using cat in a subshell substitution like this will make bash tokenize the output according to IFS, which by default includes spaces. This is the normal behavior for a for loop. Probably the easiest fix is:

while read line
     echo $line
     command $line
done < pets.txt

Note that bash will split the args up to command, howver. If you wanted the line as one arg, then just quote it:

while read line
     echo $line
     command "$line"
done < pets.txt
  • 1
    It's not cat in a subshell per se, but the semantics of for. – geekosaur May 11 '12 at 21:23
  • Right, bad wording on my part. What you say is correct. – FatalError May 11 '12 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.