Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 775
ChickenFur Avatar asked Nov 08 '12 21:11

ChickenFur


People also ask

How do I echo a line in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

How do you echo multiple lines in shell?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.


1 Answers

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

  • http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html -> 2.6.3 Command Substitution
  • http://mywiki.wooledge.org/BashFAQ/082

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

like image 128
Gilles Quenot Avatar answered Nov 03 '22 07:11

Gilles Quenot