Ways to append text to a file

I quite like this one, where I can set up a log file at the top of a script and write to it throughout without needing either a global variable or to remember to change all occurrences of a filename:

exec 3>> /tmp/somefile.log
...

echo "This is a log message" >&3
echo "This goes to stdout"
echo "This is written to stderr" >&2

The exec 3>dest construct opens the file dest for writing (use >> for appending, < for reading - just as usual) and attaches it to file descriptor #3. You then get descriptor #1 for stdout, #2 for stderr, and this new #3 for the file dest.

You can join stderr to stdout for the duration of a script with a construct such as exec 2>&1 - there are lots of powerful possibilities. The documentation (man bash) has this to say about it:

exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. [...] If command is not specified, any redirections take effect in the current shell [...].


Here are few other ways to append text to a file.

  1. Using tee

    tee -a file <<< "text text text ..."
    
  2. Using awk

    awk 'BEGIN{ printf "text text text ..." >> "file" }'
    
  3. Using sed

    sed -i '$a text text text ...' file
    sed -i -e "\$atext text text ..." file
    

Sources:

  • How to Append to End of a File in Linux

  • SED: insert text after the last line?


Using a here-document approach:

cat <<EOF >> file
> foo
> bar
> baz
> EOF

Tests:

$ cat file
aaaa
bbbb

$ cat <<EOF >> file
> foo
> bar
> baz
> EOF

$ cat file
aaaa
bbbb
foo
bar
baz