Join my Laravel for REST API's course on Udemy 👀

Append lines to the end of a file with Bash

October 16, 2020  ‐ 2 min read

At some point it is gonna be useful to write to a file with Bash. You can do so in a Bash script or directly via the command-line. To do so you use the append operator(>>).

#!/bin/bash

# 1. Set the file to write to
file='log.txt'

# 2. Append text with '>>'
echo "[INFO] caught a bass" >> $file

The >> appends to a file or creates the file if it doesn't exist. Don't confuse >> with >, the latter completely overwrites a file erasing all current lines.

Append command output to a file

So technically this is what we did with echo as well. Where the output of the echo command was appended to a file. You can use the output of other commands as well in combination with the append operator. Like the ls command for example.

#!/bin/bash

# 1. Set the file to write to
file='files_and_directories.txt'

# 2. Append text with '>>'
ls >> $file

Append multiple lines at once

Until so far we only appended single lines. But you might as well want to write multiple lines to a file at once. Tis a bit more cryptic however. But you can use cat for this.

#!/bin/bash

# 1. set the file to write to
file='log.txt'

# 2. Append multiple lines with '>>' and 'cat'
cat << EOT >> $file
[INFO] caught a bass
[INFO] and released the bass
EOT

Learning more

The best way to learn more is to use Bash. A lot. Don't forget that Google is your friend.

In case you learn well from books I would recommend these.