16

I'm trying to execute a command for each line coming from a cat command. I'm basing this on sample code I got from a vendor.

Here's the script:

for tbl in 'cat /tmp/tables'
do
   echo $tbl
done

So I was expecting the output to be each line in the file. Instead I'm getting this:

cat
/tmp/tables

That's obviously not what I wanted.

I'm going to replace the echo with an actual command that interfaces with a database.

Any help in straightening this out would be greatly appreciated.

5 Answers 5

27

You are using the wrong type of quotes.

You need to use the back-quotes rather than the single quote to make the argument being a program running and piping out the content to the forloop.

for tbl in `cat /tmp/tables` 
do 
    echo "$tbl"
done

Also for better readability (if you are using bash), you can write it as

for tbl in $(cat /tmp/tables) 
do 
    echo "$tbl"
done

If your expectations are to get each line (The for-loops above will give you each word), then you may be better off using xargs, like this

cat /tmp/tables | xargs -L1 echo

or as a loop

cat /tmp/tables | while read line; do echo "$line"; done
Sign up to request clarification or add additional context in comments.

1 Comment

The last version has the advantage of removing whitespace, too.
5

The single quotes should be backticks:

for tbl in `cat /etc/tables`

Although, this will not get you output/input by line, but by word. To process line by line, you should try something like:

cat /etc/tables | while read line
    echo $line
done

Comments

3

With while loop:

while read line
do
echo "$line"
done < "file"

Comments

3
while IFS= read -r tbl; do echo "$tbl" ; done < /etc/tables

read this.

Comments

0

You can do a lot of parsing in bash by redefining the IFS (Input Field Seperator), for example

IFS="\t\n"  # You must use double quotes for escape sequences. 
for tbl in `cat /tmp/tables` 
do 
    echo "$tbl"
done

2 Comments

'\t\n'? Have you actually tried it in bash? It will split on '\', 't', 'n', unhelpful.
Single quotes do not allow for escaping. Use double quotes. "\t\n" Otherwise, single quotes will literally preserve the meaning of '\', 't', 'n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.