Linux Io Redirection Commands

Linux I/O Redirection Commands

The “I/O” stands for input/output and with this facility
you can redirect the input and output of commands to and from files, as well as connect
multiple commands together into powerful command pipelines. To show off this facility,
we will introduce the following commands:

  • cat - Concatenate files
  • sort - Sort lines of text
  • uniq - Report or omit repeated lines
  • grep - Print lines matching a pattern
  • wc - Print newline, word, and byte counts for each file
  • head - Output the first part of a file
  • tail - Output the last part of a file
  • tee - Read from standard input and write to standard output and files

Redirecting Standard Output

1
2
$ ls -l /usr/bin > ls-output.txt
$ tree foo/ > tree-output.txt

append redirected output to a file instead of overwriting the file from the beginning:

1
$ ls -l foo/ >> tree-output.txt

Redirecting Standard Error

  • we have referred to the first three of these file streams as standard input, output and error
1
2
3
$ ls -l /bin/usr 0> ls-input.txt
$ ls -l /bin/usr 1> ls-output.txt
$ ls -l /bin/not-exist 2> ls-error.txt

Redirecting Standard Output And Standard Error To One File

1
2
3
$ ls -l /bin/usr > ls-output.txt 2>&1     # old-version

$ ls -l /bin/usr &> ls-output.txt # new-version

Disposing Of Unwanted Output

1
$ ls -l /bin/usr 2> /dev/null     # /dev/null is a special file which accepts input and does nothing with it