Linux Command: Piping (output of one command, as input of another)

A single Linux command is specialized to do one thing and one thing only.

Using the technique of piping we can send the standard output of one command as the standard input of another command. This way we can build a complex and advanced process(step-by-step) to perform complicated tasks.

Linux Command Piping
Linux Command Piping

Piping

“|” This symbol is called a pipe. We can use this symbol to send output from one command as input for another command.

$ date

Wed Jul 24 18:36:21 +06 2024

# Use cut on the output of date to get the time part
$ date | cut --delimiter " " --field 4

18:36:21

# Use the cut commadn on that, to get the hour part only
$ date | cut --delimiter " " --field 4 | cut --delimiter ":" --field 1

18
Bash

Pipe and Redirect

We can also use the pipe and redirection together. In the command below we are writing the time on a file by redirecting the final output of the “cut” command.

$ date | cut --delimiter " " --fields 4 > current_time.log

$ date | cut --delimiter " " --fields 4 >> current_time.log

$ date | cut --delimiter " " --fields 4 >> current_time.log

$ cat current_time.log

18:43:30
18:43:32
18:43:34
Bash

tee Command

We can redirect the output and also send it next step at the same time using “tee”.

Linux Command Pipelining with tee
Linux Command Pipelining with tee

Use “tee” at any step of the pipe process-

$ date | tee current_time.log | cut --delimiter " " --fields 4

19:49:54

$ cat current_time.log

Wed Jul 24 19:49:54 +06 2024
Bash

xargs Command

Not every command in Linux accepts a standard input, rather accepts some options/arguments. Like, commands like “echo”.

$ date | echo

# no output as echo does not accept any input
Bash

Using the “xargs” command we can convert output of a command to arguments.

$ date | cut --delimiter=" " --fields=4 | xargs echo
20:29:09
Bash

Similar things we can do with touch

$ date | cut --delimiter=" " --fields=4 | xargs touch
Bash

or even with rm-

# Create files
$ touch a.txt b.txt

# Add the file names to delete_files.txt
$ cat > delete_files.txt
a.txt
b.txt

# Read delete_files.txt and send that to "rm" through xargs
$ cat delete_files.txt | xargs rm

# This command works similart to the following
# rm a.txt b.txt
Bash

Another command, that I use regularly. The “rm” does not support pattern for the file/directory name. So we have to first find the files with “find”(with file name pattern) command and then delete those using “rm”.

Say we want to delete anything that ends with “:Zone.Identifier”, so the pattern is “*:Zone.Identifier”.

$ find . -iname "*:zone.identifier" | xargs rm -r
Bash

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.