Creating files with some content with shell script

Solution 1:

You can use a here document:

cat <<EOF >/home/a.config
first line
second line
third line
EOF

You can place several of these in the same script.

On OS-X the command should be:

cat > filename <<- "EOF"
file contents
more contents
EOF

Solution 2:

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

Solution 3:

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.

Solution 4:

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

Solution 5:

>\#!/bin/bash
>
>var="your text" <br>
>echo "simply put, <br>
>just so: $var" > a.config

Note that you also need to escape out certain characters to avoid them interfering with what you're trying to do, for example $ ` and " will all break such a statement unless preceded with a backslash, i.e. \` \$ or \"

so if we define the following:

var="100"

the following would not behave as expected:

echo "simply put,
just "lend" me US$ $var" > a.config

but the following would work correctly:

echo "simply put,
just \"lend\" me US\$ $var" > a.config