3.1 Input, Output and Redirection

Standard in- and output

Each process has always these three “files” open: STDIN (input), STDOUT (output) and STDERROR (error). By default, STDIN is attached to the keyboard (typing the file name) and the others to the screen (displaying output and error).

Redirection

All three “files” may be redirected. For instance, STDOUT can be redirected to a file using the operator “>”.

Redirecting STDOUT to a File (Example 1)

echo "Hello world"
#Hello world!
echo "Hello world" > out.txt
cat out.txt
#Hello world

Redirecting STDOUT to a File (Example 2)

ls out.txt other.txt
#ls: cannot access other.txt: No such file or directory out.txt
ls out.txt other.txt > ls.txt
#ls: cannot access other.txt: No such file or directory
cat ls.txt
#out.txt

In the previous examples, the generated output of “echo” and “ls” is redirected using “>” (error message is not).

If we want to redirect STDERR to a file, we need to use “2>”

ls out.txt other.txt 2> ls.err
#out.txt
cat ls.err
#ls: cannot access other.txt: No such file or directory

We now save the error message in a file called ls.err by using “2>”

Of course, it can be annoying to type the same command twice to save the output and the error message in different files. So, we can simply type “2>” to redirect STDERR after redirecting STDOUT using “>” on the same line code.

ls out.txt other.txt > ls.txt 2> ls.err
ls out.txt other.txt > ls.all 2>&1

Note: 2>&1 means “redirect STDERR to the file where STDOUT goes”, in our case it would go to ls.all