ChickenFur
ChickenFur

Reputation: 2400

How to echo lines of file using bash script and for loop

I have a simple file called dbs.txt I want to echo the lines of that file to the screen using a for loop in bash.

The file looks like this:

db1
db2
db3
db4

The bash file is called test.sh it looks like this

for i in 'cat dbs.txt'; do
echo $i
done
wait

When I run the file by typing:

bash test.sh

I get the terminal output:

cat dbs.txt

instead of the hoped for

db1
db2
db3
db4

The following bash file works great:

cat dbs.txt | while read line
do
echo "$line"
done

Why doesn't the first script work?

Upvotes: 13

Views: 82259

Answers (4)

Todor
Todor

Reputation: 296

You can use the shell builtin read instead of cat. If you process just a single file and it's not huge, perhaps the following is easier and more portable than most solutions:

#!/bin/sh

while read line
do
    printf "%s\n" "$line"
done < "$1"

I remember reading somewhere that printf is safer than echo in the sense that the options that echo accepts may differ across platforms. So building a habit of using printf may be worthwhile.

For description of the read builtin, check the manual pages of your shell.

Upvotes: 18

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185219

You need command substitution shell feature. This require the POSIX expression $().

Please, don't use backticks as others said.

The backquote (`) is used in the old-style command substitution, e.g.

foo=`command`

The

foo=$(command)

syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See

Despite of what Linus G Thiel said, $() works in sh, ash, zsh, dash, bash...

Upvotes: 5

Pedro del Sol
Pedro del Sol

Reputation: 2841

you need backticks rather than single quotes

` vs '

Upvotes: 1

Linus Thiel
Linus Thiel

Reputation: 39233

You need to execute a sub-shell and capture the output, like this:

for i in `cat dbs.txt`; do
echo $i
done
wait

Note the backticks ` instead of the single-quotes.

In bash you can also use $(command):

for i in $(cat dbs.txt); do
echo $i
done
wait

Upvotes: 11

Related Questions