pipe Command in Linux

Learn via video courses
Topics Covered

Overview

The pipe command in Linux, represented by the vertical bar symbol '|', is an essential tool for command-line enthusiasts and professionals alike. The primary purpose of the pipe command is to connect the output of one command directly into the input of another. This command allows users to chain multiple commands together in a single line, thereby improving efficiency and enabling the creation of more complex commands.

Syntax of pipe Command in Linux

The basic syntax of the pipe command in Linux is as follows:

Where:

  • command1: This is the initial command whose output will serve as input to the next command.
  • | (pipe symbol): This symbol is the pipe command itself. It facilitates the transfer of output from command1 into command2.
  • command2: This is the subsequent command that receives the output of command1 as its input.

Options in pipe Command in Linux

Example Usages

  • Pipe command to filter directory listing:

    Output:

    Explanation: This command uses 'ls -l' to list all files and directories in the current directory. The output is piped into 'grep' command, which filters out only those lines that contain '.txt'.

  • Pipe command to sort process based on memory usage:

    Output:

    Explanation: This command first uses 'ps aux' to get a snapshot of current processes. The output is then piped into the 'sort' command, which sorts the processes based on the fourth field (memory usage).

Tips

  • The power of the pipe command in Linux lies in its ability to chain multiple commands together.

  • It's crucial to understand the input and output requirements of each command while using the pipe command.

Advanced Use Cases of pipe Command in Linux

  • Pipe command to find the number of files in a directory:

    Output:

    Explanation: This command lists the files and directories, filters for files (using '^-' which matches lines starting with '-'), and then pipes the output to 'wc -l' to count the number of lines, thereby giving the number of files.

  • Pipe command to display the five most CPU-intensive tasks:

    Output:

    Explanation: This command gets a snapshot of current processes, sorts them in descending order of CPU usage, and then uses 'head' to output the top five entries.

  • Pipe command to check disk usage of directories:

    Output:

    Explanation: This command checks the disk usage of directories, sorts them in human-readable format in descending order, and then outputs the top 10 entries.

Conclusion

  • The pipe command in Linux is a powerful tool for chaining commands and transforming data.

  • A good understanding of each command's input and output is crucial to use the pipe command effectively.

  • Advanced usages of the pipe command in Linux enable creation of complex commands to achieve specific goals.