Input/Output Redirection

πŸ“Œ Bash Redirection

  • In Bash (or other Linux shells), when a program is executed, it uses three standard Input/Output streams, each one represented by a numeric file descriptor:

    • 0 - stdin : the standard input stream (printed on the screen by default)

    • 1 - stdout : the standard output stream

    • 2 - stderr : the standard error stream (printed on the screen by default)

  • All three streams can be redirected.

sudo ls /root 
	[sudo] password for user: # This is the std input
	snap	# This is the std output

ls /root
	ls: cannot open directory '/root': Permission denied # This is the std error

Redirection symbols

  • The > symbol is used for redirect stdout to a file.

    • If the redirection points to a file that already exists, this file will be overwritten!

ls /etc/ > etc-contents.txt
# The content of the file is the same as the normal content of the command
  • The >> symbol is used to append stdout to a file.

  • The < symbol is used for redirect stdin input to a command.

  • Redirect standard error to a file.

    • To suppress the error messagges from being displayed on the screen, redirect stderr to /dev/null.

Pipes

  • | - Pipes can connect the stdout of one command to the stdin of another command.


Last updated

Was this helpful?