A Bash Script Shortcut to Echo Multiple Lines To A New File

Script or batch file writing can be very rewarding, especially when the script written works as planned. What is particularly rewarding is when a shortcut is found that greatly simplifies how the script is written and executed. Here is a couple of shortcuts that I picked up from the Internet. The end result all seem to be the same.

This is not entirely true, pending on the content, the results may not be as expected. as in the case of !-f may produce something else using the echo, however, using cat, produced the desired results. You may have to play with these to find the one that works for you in your given task.

Originally, this approach would have been used. This is still good to use for small files.

#!/bin/bash
echo "This is line one." > /opt/test.test
echo "This is line two." >> /opt/test.test
echo "# This line is commented out" >> /opt/test.test
echo >> /opt/test.test
echo "The line above is intentionally blank." >> /opt/test.test

However, when the files become larger, an alternate approach is more desirable. According to a forum sited below, the -d option for read is unique to /bin/bash, so be certain to use /bin/bash and not /bin/sh.

#!/bin/bash
# Create test.test file
read -d '' my_test <<"TESTCONF"
This is line one.
This is line two.
# This line is commented out

The line above is intentionally blank.
}
TESTCONF
echo "$my_test" > /opt/test.test

Even cleaner than the example above is this code. It is noted from a source below to note have any spaces/nulls after the EOF, otherwise
the script will keep going trying to find the ‘EOF’.

#!/bin/bash
cat > /opt/test.test << EOF
This is line one.
This is line two.
# This line is commented out

The line above is intentionally blank.
EOF

Even cleaner than the examples above.

#!/bin/bash
echo "This is line one.
This is line two.
# This line is commented out

The line above is intentionally blank.
" > /opt/test.test

Source(s)
http://stackoverflow.com/questions/5098591/read-illegal-option-d
http://www.linuxmisc.com/12-unix-shell/c078ed459a506312.htm
http://www.rudder-project.org/rudder-doc-2.8/rudder-doc.html#_install_rudder_server