How to echo file lines using bash script and for loop

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

The file is as follows:

db1 db2 db3 db4 

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

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

When I run the file by typing:

 bash test.sh 

I get terminal output:

 cat dbs.txt 

instead of the expected

 db1 db2 db3 db4 

The following bash file works fine:

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

Why does the first script not work?

+6
source share
4 answers

You can use the built-in read shell instead of cat . If you process only one file, and it is not huge, perhaps the following is simpler and more portable than most solutions:

 #!/bin/sh while read line do printf "%s\n" "$line" done < "$1" 

I remember reading somewhere that printf safer than echo in the sense that the options that echo accepts may vary on different platforms. Therefore, creating the habit of using printf can be useful.

For a description of the built-in read check the manual pages of your shell.

+9
source

You need a command expansion function. This requires the POSIX expression $() .

Please do not use backlinks as others say .

Countdown ( ` ) is used in old-style lookup, for example.

 foo=`command` 

 foo=$(command) 
Use syntax instead

. The backslash in $ () is less surprising, and $ () is easier to embed. Cm

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

+4
source

You need to execute a sub-shell and capture the output, for example:

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

Pay attention to backticks `instead of single quotes.

In bash, you can also use $(command) :

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

you need backlinks, not single quotes

`vs'

+1
source

All Articles