I/O redirection is used in shell scripting. This feature enables one to take the output of a command and redirect it as an input for another command, or a command can take the input from a file instead of from the standard input stream or from the terminal. The whole process helps connect data streams in various ways.

Input/Output redirection and pipes

One of the important features of the shells is the ability to connect commands. For example, one can take the output of a command and redirect it as an input for another command. Or a command can take the input from a file instead of the keyboard. The whole process is accomplished thought Input/Output redirection and pipes.

The specific syntax for I/O redirection is dependent on the that you are using.

stdin, stdout, stderr

Every command or program executed by the shell has 3 data streams associated with it:

  1. standard input (stdin, with a file descriptor of 0) – where commands get their input from (by default, keyboard input provided by the terminal).
  2. standard output (stdout, file descriptor 1) – where commands send their output (by default, the terminal display).
  3. standard error (stderr, file descriptor 2) – where commands send their error and warning messages (by default, the terminal display).

By default, stdin is the keyboard and where command usually take its input, stdout is the where a command sends its output and stderr is the place where errors are printed.

Shell redirection

I/O Redirection allows the shell to manipulate these file descriptors. A common use case is the redirection of a command’s standard output to another file. A single > operator truncates the file to zero length and then over-writes the file with the output of the command:

# Redirecting the output of ls command to a file
$ ls -lt > file_ls.txt

Two greater-than signs (>>) append to a file, without truncating it:

$ ./script >> log_file.txt

Both stdout and stderr can be redirected to the same file:

# Append the output in commands.log and send the error(2)
# where it points the stdout(&1)
$ ls -yz >> commands.log 2>&1

The less-than sign (<) is used for input redirection:

$ cat < input_file.txt

Some commands, e.g., ls, do not take any input so any input redirected to such commands is ignored (not read by the program).

Command can have both input and output redirection at the same time:

$ ./script < input_file > output.log

Further reading

Related tags

References