[linux] How to write multiple line string using Bash with variables?

How can I write multi-lines in a file called myconfig.conf using BASH?

#!/bin/bash
kernel="2.6.39";
distro="xyz";

echo <<< EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL >> /etc/myconfig.conf;
cat /etc/myconfig.conf;

This question is related to linux bash bash4

The answer is


#!/bin/bash
kernel="2.6.39";
distro="xyz";

cat > /etc/myconfig.conf << EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL

this does what you want.


I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

If you do not want variables to be replaced, you need to surround EOL with single quotes.

cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

Previous example:

$ cat /tmp/myconfig.conf 
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 

Below mechanism helps in redirecting multiple lines to file. Keep complete string under " so that we can redirect values of the variable.

#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt

Content of a.txt is

line 1, 2.6.39
line 2,

Content of b.txt is

line 2, ${kernel}
line 2,

The heredoc solutions are certainly the most common way to do this. Other common solutions are:

echo 'line 1, '"${kernel}"'
line 2,
line 3, '"${distro}"'
line 4' > /etc/myconfig.conf

and

exec 3>&1 # Save current stdout
exec > /etc/myconfig.conf
echo line 1, ${kernel}
echo line 2, 
echo line 3, ${distro}
...
exec 1>&3  # Restore stdout