DEV Community

Kervie Sazon
Kervie Sazon

Posted on

Linux Fundamentals - Part 12: Linux Redirection, Pipes, and Command Chaining (Applied Text Processing)

Standard Input, Output and Error

Linux command uses three streams:

Stream Name What it does
0 stdin Input to the command
1 stdout Normal output
2 stderr Error messages

Example:

ls my_folder
Enter fullscreen mode Exit fullscreen mode

If the my_folder exists - output goes to stdout.
If it doesn’t - error goes to stderr.

Redirect error only:

2>

ls fake_folder 2> error.txt
Enter fullscreen mode Exit fullscreen mode

The error message is saved to error.txt, not shown on screen.

Output Redirection (> and >>)

> - Overwrite file
It sends output to a file.

Example:

echo "My name is Kervie" > kerv.txt
Enter fullscreen mode Exit fullscreen mode

Explanation:
The terminal stays empty. The ouput goes into kerv.txt. Existing content of the file kerv.txt is replaced by "My name is Kervie".

>> - Append to file
It adds output to the end of the file.

Example:

echo "I am 23 years old" >> kerv.txt
Enter fullscreen mode Exit fullscreen mode

The terminal is still empty because the message save to kerv.txt file.

To view the kerv.txt file:

cat kerv.txt
Enter fullscreen mode Exit fullscreen mode

Output:

My name is Kervie
I am 23 years old
Enter fullscreen mode Exit fullscreen mode

Explanation:
Keeps old content. Adds new output at the bottom.

Pipes (|) - Connecting Commands

Used to chain multiple commands using the pipe (|) operator, passing the stdout of one process to the stdin of the next.

Example:

ls | grep '.txt`
Enter fullscreen mode Exit fullscreen mode

This is to filer only .txt files on the lists file.

Screenshot for more understanding.

Another Example:

cat textpro.sh | grep 'gmail' | sort > sorted_results.txt
Enter fullscreen mode Exit fullscreen mode

This command sequence uses cat to print textpro.txt, greps for lines that contain ‘gmail’, sorts them, and then writes the output to sorted_results.txt.

Screenshot for more understanding.

Today, I learned how Linux uses standard input, output, and error streams, and how redirection operators like > and >> can send command output to files instead of displaying it on the terminal. I also learned how pipes (|) allow the output of one command to become the input of another, making it possible to process text step by step. Overall, this lesson showed me how combining simple commands can create powerful and efficient workflows when working with text in the Linux terminal.

Top comments (0)