Linux Basic Commands

I/O Redirection

Basic I/O streams are:

  • Standard Input (stdin)  -keyboard
  • Standard Output (stdout)  -screen display
  • Standard Error (stderr)  -usually screen

 

Handle Name Description
0 stdin Standard input
1 stdout Standard output
2 stderr Standard error

 

 

This lesson will teach you how to redirect standard output to files, devices, and even to the input of other commands.

Also how to redirect standard input from terminal and pipeing.

 

 

Standard Output (stdout)

In most cases the standard output is display (screen). We can redirect it to a file using the following commands.

 

Redirect to a file

1. Create file if doesn't exists or overwrite existing file (operator > )

$ ls > file.txt

$ echo "Some text" > file.txt

$ cat file*

 

2. Append to the end of file (operator >> )

$ echo 'Second line ! ' >> file.txt

Use single quotes when you want to echo exclamation mark (!).

 

 

Standard Input (stdin)

Standard input is keyboard. To use input from a file we can use the following command (operator < ).

$ sort < file_input.txt

$ sort < file_input.txt > file_output.txt

 

 

Standard Error (stderr)

In most cases errors are displayed on screen. If we want to redirect errors into file we will use:

  • 2>   -will create file or overwrite existing file
  • 2>> -will apend error to the file

 

$ program_with_error 2> error.log

$ bad_command 2> error.log

 

If we want to redirect both stdout and stderr we will use &> or &>> .

$ command &> find.txt

$ find ~ -name dog > find.txt 2>&1

 

 

When the standard error is not screen we can redirect stderr to screen e.g to stout by: $ command 2>&1 where &1 is the reference for the stdout.

 

 

 

Pipe

The standard output of one command is fed into the standard input of another (operator | ).

$ ps -aux | grep node