Creating files with some content with shell script

You can use a here document:

cat <<EOF >filename
first line
second line
third line
EOF

You can place several of these in the same script.


If you've got variables like $1 or $HOMEDIR in your text then these normally get evaluated and substituted with actual values. If you want to prevent these from getting substituted then you need to quote the opening limit string (EOF in example below) with single quote 'EOF', double quote "EOF" or precede it with backslash \EOF

Closing limit string stays as is. EOF

This is especially useful if you are writing shell scripts to a file.

cat << 'EOF' >/etc/rc.d/init.d/startup
case $1 in
    start)
        start 
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
       pid=$(tomcat_pid)
        if [ -n "$pid" ]
        then
           echo "Tomcat is running with pid: $pid"
        else
           echo "Tomcat is not running"
        fi
        ;;
esac

EOF

Refer Example 19.7 Parameter Substitution Turned off in Here Documents


Like so:

#!/bin/bash

var="your text"
echo "simply put,
just so: $var" > a.config

For further info, see Input/Output part of abs.
Hope, this helps.


file="/tmp/test.txt"
echo "Adding first line" > $file
echo "Adding first line replaced" > $file
echo "Appending second line " >> $file
echo "Appending third line" >> $file
cat $file

> to add/replace the content ( here actual content got replaced by the 2nd line)
>> to append

Result
Adding first line replaced
Appending second line
Appending third line