1

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!

1 Answer 1

5

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
2
  • 1
    It's not cat in a subshell per se, but the semantics of for.
    – geekosaur
    Commented May 11, 2012 at 21:23
  • Right, bad wording on my part. What you say is correct.
    – FatalError
    Commented May 11, 2012 at 21:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .