What Does /Dev/Null Mean in a Shell Script? [Duplicate]

What Does /Dev/Null Mean in a Shell Script? [Duplicate]

I've started learning bash scripting by using this guide:

However I got stuck at the first script:

cd /var/log
cat /dev/null > messages
cat /dev/null > wtmp
echo "Log files cleaned up."

What do lines 2 and 3 do in Ubuntu (I understand cat)? Is it only for other Linux distributions? After running this script as root, the output I get is Log files cleaned up. But /var/log still contains all the files.

1

5 Answers

Assuming the commands succeeded, /var/log/messages and /var/log/wtmp still exist but are now blank.

Shell Redirection

> is a redirection operator, implemented by the shell. Its syntax is:

command > file

This redirects command's standard output to file.

  • file may also be a device node.
  • If file doesn't exist, it is created as a regular file.
  • If file already exists as a regular file and is non-empty, it is overwritten. This is typically the case in the commands you ran, where you redirected the output of cat /dev/null to messages and wtmp.
  • If file already exists as a symbolic link, the link's target is used.
  • If file already exists as a directory, you'll get an error like bash: file: Is a directory.

(Of course, these operations may fail for other reasons, such as lack of permissions or a filesystem error.)

The >> redirection operator is similar, but it appends to the end of non-empty regular files instead of overwriting their contents. (Another redirection operator is <. command < file uses file as command's standard input.)

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.