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;
Solution 1:
The syntax (<<<
) and the command used (echo
) is wrong.
Correct would be:
#!/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
cat /etc/myconfig.conf
This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash
.
Solution 2:
#!/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.