Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand pipe and redirection command

Tags:

bash

pipe

I want to understand the real power of pipe and redirection command.As per my understanding,| takes the output of one command result as the input of itself. And, > is helps in output redirecting .If it is so,

find . -name "*.swp" | rm 
find . -name "*.swp" > rm 

why this command is not working as expected .For me above command means

  1. Find the all files recursively whose extension is .swp in current directory .
  2. take the output of 1. and remove all whose resulted files .

FYI,yes i know how to accomplish this task . it can be done by passing -exec flag .

find . -name "*.swp"-exec rm -rf {} \;

But as I already mentioned,i want to accomplish it with > or | command.
If i was wrong and going in wrong direction,please correct me and explain redirection and pipe command. Where we use whose commands ? please dont mention simple book examples i read all whose thing . try to explain me some complicated thing .

like image 398
Paritosh Piplewar Avatar asked Jul 19 '26 09:07

Paritosh Piplewar


1 Answers

I'll break this down by the three methods you have shown:

  • > will redirect all output from find into a file named rm (will not work, because you're just appending to a file).
  • | will pipe output from find into the rm command (will not work, because rm does not read on stdin)
  • -exec rm -rf {} \; will run rm -rf on each item ({}) that find finds (will work, because it passes the files as argument to rm).

You will want to use -exec flag, or pipe into the xargs command (man xargs), not | or > in order to achieve the desired behavior.

EDIT: as @dmckee said, you can also use the $() operator for string interpolation, ie: rm -rf $(find . -name "*.swp") (this will fail if you have a large number of files, due to argument length limits).

like image 79
neersighted Avatar answered Jul 21 '26 10:07

neersighted



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!