13

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?

3
  • 1
    fwiw, it's a better practice to use while read instead of for i in $(cat dbs.txt) Commented Nov 8, 2012 at 21:50
  • the first one (even when fixed) would not echo line-by-line if any of the lines contain spaces Commented Nov 9, 2012 at 8:06
  • Your single quotes should be back ticks: <pre>for i in cat dbs.txt; do echo $i done wait</pre> Commented Nov 15, 2017 at 18:50

4 Answers 4

18

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.

Sign up to request clarification or add additional context in comments.

Comments

11

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

1 Comment

See my post, backticks are discouraged.
5

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...

Comments

1

you need backticks rather than single quotes

` vs '

1 Comment

See my post, backticks are discouraged.

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.