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?
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.
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.
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With