Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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)
do
     echo $line
     "command $line"
done

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.

Thanks!

share|improve this question

1 Answer 1

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
do
     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
do
     echo $line
     command "$line"
done < pets.txt
share|improve this answer
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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