Skip to content

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:

$ echo "hello"
hello
$ echo $?
0

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:

$ asdioeie
asdioeie: command not found
$ echo $?
127

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 >

$ echo "hello" > output.txt
dpena@dpena:~$ cat ./output.txt 
hello

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

$ echo "hello" 1> output.txt
$ cat ./output.txt 
hello

If instead we want to capture the error, we would use 2 (stderr)

$ echo "hello" 2> output.txt
hello
~$ cat ./output.txt 

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.

$ grep -r hello /sys/ 2> /dev/null
$ 

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:

$ ping google.com 1> /dev/null
only shows output when ping is failing

If we want all output (stdout and stderr) to be ignored, we can use the wildcard &>

$ grep -r hello /sys/ &> /dev/null

We can test a URL without saving anything by redirecting output to /dev/null, for example:

$ wget -O /dev/null http://miserver.com/arhivoloquesea

It will not consume disk space since everything goes to /dev/null