Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print output of cat statement in bash script loop

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.

like image 429
geoffrobinson Avatar asked Jul 29 '11 03:07

geoffrobinson


People also ask

How can I loop over the output of a shell command?

#!/bin/bash while IFS= read -a oL ; do { # reads single/one line echo "${oL}"; # prints that single/one line }; done < <(ps -ewo pid,cmd,etime | grep python | grep -v grep | grep -v sh); unset oL; Note: You can use any simple or complex command/command-set inside the <(...) which may have multiple output lines.

Can you use cat in a bash script?

The “cat” command in Bash stands for “concatenate”. This command is very frequently used for viewing, creating, and appending files in Linux.

What is cat << EOF >>?

This operator stands for the end of the file. This means that wherever a compiler or an interpreter encounters this operator, it will receive an indication that the file it was reading has ended.

What is cat << in Linux?

Cat is short for concatenate. This command displays the contents of one or more files without having to open the file for editing. In this article, learn how to use the cat command in Linux. A system running Linux. Access to a terminal window / command line.


1 Answers

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
like image 64
Soren Avatar answered Oct 05 '22 23:10

Soren