Introduction
Bash Interpreter
To understand how executions work through the Bash interpreter, let’s look at some basic concepts:
1. Script execution return codes
All Unix commands have an execution completion code (Status). To know the status code of the last executed command, we write:
This is the same as:
$ echo "hello" | echo $?
The code 0 indicates that the command finished successfully.
2. Script execution error codes
If, for example, we execute something that results in an error, such as a command that does not exist:
By default, if not specified, execution output is sent to stdout and stderr:
- Digit 1 indicates output written to stdout
- Digit 2 indicates output written to stderr
That is why we see output on the normal console and also behind the scenes written to stderr.
3. Writing execution output to a file
We can write the execution result to a file using >
But with > we can specify which type of output we want, for example:
stdout and stderr
As you remember, 1 belongs to stdout and 2 belongs to stderr
Therefore, if we write 1>, it will write whatever goes to stdout into the file output.txt
If instead we want to capture the error, we would use 2 (stderr)
The file is empty because the execution did not write to stderr since there was no error.
4. /dev/null, what is it?
/dev/null is a file that exists on all Unix systems and automatically discards anything written to it.
It is very useful for handling command execution output (as we have seen previously).
For example, if I run a command prone to errors:
$ grep -r hello /sys/
grep: /sys/devices/system/clockevents/power/autosuspend_delay_ms: Input/output error
grep: /sys/devices/system/clockevents/clockevent6/unbind_device: Permission denied
....
....
etc..
In this case, it will print a lot of errors to the console, so we can tell it to send stderr to a file — in this case to /dev/null since we are not interested in reviewing the errors, we just know it failed and do not want to see more.
Much better output, not so verbose.
We can also listen only to negative results by sending the successful results (those that would go to stdout) to /dev/null and discarding them, for example:
If we want all output (stdout and stderr) to be ignored, we can use the wildcard &>
We can test a URL without saving anything by redirecting output to /dev/null, for example:
It will not consume disk space since everything goes to /dev/null