Suppressing Command Output - Shell Scripting

There are times when you don’t want to display any output from your script. This often occurs if you’re running a script as a background process. If any error messages occur from the script while it’s running in background, the shell e-mails them to the owner of the process. This can get tedious, especially if you run scripts that generate minor nuisance errors.

To solve that problem, you can redirect STDERR to a special file called the null file. The null file is pretty much what it says it is, a file that contains nothing. Any data that the shell outputs to the null file is not saved, thus lost.

The standard location for the null file on Linux systems is /dev/null. Any data you redirect to that location is thrown away and doesn’t appear:

$ ls -al /dev/null
$ cat /dev/null

This is a common way to suppress any error messages without actually saving them:

$ ls -al badfile test16 2/dev/null
-rwxr--r-- 1 rich rich 135 Oct 29 19:57 test16*

You can also use the /dev/null file for input redirection as an input file. Since the /dev/null file contains nothing, it is often used by programmers to quickly remove data from an existing file without having to remove the file and recreate it:

$ cat testfile
This is the first line.
This is the second line.
This is the third line.
$ cat /dev/null testfile
$ cat testfile

The file testfile still exists on the system, but now it is empty. This is a common method used to clear out log files that must remain in place for applications to operate.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Shell Scripting Topics