How to access stderr and stdout?
Stdout and stderr are streams of data, both of which are treated as a file in Linux. If you wish to perform any action on these, you use a file descriptor that uniquely identifies the file stream. The file descriptor for stdout is 1 and for stderr is 2.
To access them separately, let’s see the following command which is performed on the same script file which was used in the previous example.
./script.sh 1>stdout.txt
In this, you can see that the output contains standard errors but the standard output was not displayed. This is because the stdout stream was sent to the stdout.txt file, and you can see that the stdout.txt file contains the standard output.
While writing a shell script, we may want to discard the standard error from the output. Whatever stream we may want to suppress from the output, that stream of data can be written into /dev/null. You could write that data into another file, just like the above example, but if you have no use for that data, why would you want to waste memory on it, it’s better to discard it completely. Let’s see the following example
./script.sh 2>/dev/null
And just like that, we have removed the stderr from the output. If you wish to discard the complete output, you can use the following command
command >/dev/null 2>&1
The &> command redirects the output of the file descriptor which is mentioned on the left (in the above command, the output of 2) to the stream of file descriptor mentioned on the right-hand side. So, the output of stderr (2) gets redirected to stdout(1), which in turn gets written in /dev/null and thus gets destroyed.
Secure File Deletion
‘/dev/null’ finds utility in secure file deletion. By redirecting ‘/dev/null’ to a file, you can effectively overwrite its content with null bytes, making it challenging to recover any meaningful data.
For example:
cat /dev/null > sensitive_file
This command replaces the contents of ‘sensitive_file’ with null bytes, ensuring its secure deletion.
Cleaning Log Files
Log files can accumulate substantial data over time. To clear log files without interrupting running services, you can redirect their content to ‘/dev/null.’
For example:
cat /dev/null > /var/log/syslog
This command empties the ‘syslog’ file by redirecting its content to ‘/dev/null,’ effectively cleaning the log without deleting the file itself.
Tips and Tricks:
- Redirecting standard output to ‘/dev/null’: ‘command > /dev/null’
- Redirecting standard error to ‘/dev/null’: ‘command 2> /dev/null’
- Redirecting both output and error to ‘/dev/null’: ‘command >/dev/null 2>&1’
What is /Dev/Null in Linux?
If you have been learning shell programming, you may already have come across something like /dev/null. In this article, we will understand what it is and how it is used. Let’s start off by understanding what /dev is.
Contact Us