0
0
Linux CLIscripting~5 mins

Pipe operator (|) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to use the output of one command as the input for another command. The pipe operator (|) connects commands so data flows smoothly between them without saving to a file.
When you want to count how many files are in a folder by listing them and then counting the lines.
When you want to find a specific word in a list of running processes.
When you want to sort a list of users alphabetically after listing them.
When you want to see only the top few lines of a long output.
When you want to filter system logs to show only error messages.
Commands
This command lists all files and folders in long format, then counts how many lines the list has. It tells you how many items are in the current directory.
Terminal
ls -l | wc -l
Expected OutputExpected
12
-l - Lists files in long format with details
This command shows all running processes and then filters the list to show only those related to 'sshd'. It helps find if the SSH service is running.
Terminal
ps aux | grep sshd
Expected OutputExpected
root 1234 0.0 0.1 123456 2345 ? Ss 10:00 0:00 /usr/sbin/sshd -D user 5678 0.0 0.0 234567 1234 pts/0 S+ 10:05 0:00 grep sshd
aux - Shows all processes with detailed info
This command reads the system log file and filters lines containing the word 'error'. It helps quickly find error messages in logs.
Terminal
cat /var/log/syslog | grep error
Expected OutputExpected
Jun 10 10:00:01 myhost systemd[1]: error: Failed to start service Jun 10 10:05:23 myhost kernel: error: Disk failure detected
Key Concept

If you remember nothing else from this pattern, remember: the pipe (|) sends the output of one command directly into another command as input.

Common Mistakes
Using a space before or after the pipe incorrectly, like 'ls -l |wc -l' without spaces.
The shell requires spaces around the pipe to recognize it as a separate operator.
Always put spaces before and after the pipe: 'ls -l | wc -l'.
Trying to pipe commands that do not produce output or expect input, like 'cd /home | ls'.
'cd' changes directory and does not output data, so piping it to 'ls' does nothing useful.
Run 'cd /home' first, then run 'ls' separately.
Using pipe when you want to save output to a file instead of passing it to another command.
Pipe sends output to another command, not to a file, so the output won't be saved.
Use redirection operator '>' to save output to a file, e.g., 'ls -l > files.txt'.
Summary
The pipe operator (|) connects commands by sending output from one as input to another.
It helps combine simple commands to perform complex tasks without temporary files.
Always use spaces around the pipe and ensure the first command produces output the second can use.