Skip to main content

Linux I/O Redirection

 

Standard Input, Output, and Error Overview

Name

Default Destination

Use in Redirection

File Descriptor Number

STDIN

Computer keyboard

< (same as 0<)

0

STDOUT

Computer monitor

> (same as 1>)

1

STDERR

Computer monitor

2>

2

Common Bash Redirectors

Redirector

Explanation

> (same as 1>)

Redirects STDOUT. If redirection is to a file, the current contents of that file are overwritten.

>> (same as 1>>)

Redirects STDOUT in append mode. If output is written to a file, the output is appended to that file.

2>

Redirects STDERR.

2>&1

Redirects STDERR to the same destination as STDOUT. Notice that this has to be used in combination with normal output redirection, as in ls whuhiu > errout 2>&1.

< (same as 0<)

Redirects STDIN.

 

Exercise 2-2 Using I/O Redirection and Pipes

  1. Open a shell as user student and type cd without any arguments. This ensures that the home directory of this user is the current directory while working on this exercise. Type pwd to verify this.

  2. Type ls. You’ll see the ls command output onscreen.

  3. Type ls > /dev/null. This redirects STDOUT to the null device, with the result that you will not see it.

  4. Type ls ilwehgi > /dev/null. This command shows a “no such file or directory” message onscreen. You see the message because it is not STDOUT, but rather an error message that is written to STDERR.

  5. Type ls ilwehgi 2> /dev/null. Now you will no longer see the error message.

  6. Type ls ilwehgi /etc 2> /dev/null. This shows the contents of the /etc folder while hiding the error message.

  7. Type ls ilwehgi /etc 2> /dev/null > output. In this command, you still write the error message to /dev/null while sending STDOUT to a file with the name output that will be created in your home directory.

  8. Type cat output to show the contents of this file.

  9. Type echo hello > output. This overwrites the contents of the output file. Verify this by using cat output again.

  10. Type ls >> output. This appends the result of the ls command to the output file. Type cat output to verify.

  11. Type ls -R /. This shows a long list of files and folders scrolling over your computer monitor. (You might want to press Ctrl-C to stop [or wait some time]).

  12. Type ls -R /. | less. This shows the same result, but in the less pager, where you can scroll up and down using the arrow keys on your keyboard.

  13. Type q to close less. This will also end the ls program.

  14. Type ls > /dev/tty1. This gives an error message because you are executing the command as an ordinary user, and ordinary users cannot address device files directly (unless you were logged in to tty1). Only the user root has permission to write to device files directly.