With the IO redirection feature, we can easily manipulate the input and output of files or other information.

Standard Output

The standard output stream is usually used to print the output of a program to a file, its file descriptor is 1.

Output Text to a File

1
2
echo 'This is a text for test' > fresh_file
cat fresh_file
img

Output text to fresh_file

Output Result to a File

1
2
ll -a > dir_list_file
cat dir_list_file
img

Output result to dir_list_file

Append Text to a File

1
2
echo 'This is a text for test' >> fresh_file
cat fresh_file
img

Append text to fresh_file

Append Result to a File

1
2
ll -a >> dir_list_file
cat dir_list_file
img

Append result to dir_list_file

Standard Input

Standard input streams are usually used to print the contents of a file to a screen, its file descriptor is 0.

Read Text from a File

1
cat < fresh_file
img

Read text from fresh_file

Copy Text from a File to Another File

1
cat > new_fresh_file < fresh_file
img

Copy text from fresh_file to new_fresh_file

Multi-line Text to a File Using Here Documents

1
2
3
4
5
6
cat > new_here_document_file << EOF
First line
Second line
Third line
EOF
cat new_here_document_file
img

Input here documents to new_here_document_file

Standard Error

Standard error streams are typically used to print error content from the output of a program to a file, its file descriptor is 2.

Redirects Error Messages to a File

1
2
cat non_existing_file 2> error_log
cat error_log
img

Redirects error messages to error_log file

Standard error streams are typically used to print error content from the output of a program to a file, its file descriptor is 2.

Suppress the Error Messages

1
cat non_existing_file 2> /dev/null
img

Redirects error messages to /dev/null

Standard error streams are typically used to print error content from the output of a program to a file, its file descriptor is 2.

Show Error Messages and Output Standard Results to a File

1
2
cat non 2>&1 > std_output_result    # file "non" not found
cat std_output_result    # no standard output
img

Show error messages on screen and output standard results to a file

1
2
cat fresh_file 2>&1 > std_output_result    # file fresh_file found
cat std_output_result    # no standard error
img

Show error messages on screen and output standard results to a file

References 3.6 Redirections

Buy me a coffeeBuy me a coffee