Fix Those Pipes

The pipe command in this post didn’t work with every command, so now we’re going to fix those pipes. Remember that the pipe takes the standard out from one command and turns it into standard in for another and how that doesn’t always work with every command. One command it doesn’t work with is rm. Let’s start by making a file.

Alpha:~ computerlamp$ echo "Mario Rocks!" > Nintendo

Now we’re going to use find to remove it. I know that’s kind of silly, but hey, we need to be able to try these things out. Here’s the command to use find and rmove it:

Alpha:~ computerlamp$ find . -name 'Nintendo' | rm

What we get back is an error telling us how rm works:

Alpha:~ computerlamp$ find Nintendo | rm
usage: rm [-f | -i] [-dPRrvW] file ...
       unlink file

This looks like I can’t use find with rm and a pipe.

Wait, this is Linux, there’s another way around this, I can fix those pipes! It’s the command xargs. It takes the output from one command and turns it into the command line string for another. This is for those commands that don’t read input from standard in, like ls does.

It works like:

Alpha:~ computerlamp$ find . -name 'Nintendo' | xargs rm

See where I stuck that xargs? Try it and the error we saw before has gone away! I fixed those pipes!

But wait, isn’t this a different way of doing what the -exec flag to find did that we saw in this post? Well, yes it is. It’s also a more efficient way of doing things.

The -exec flag works on each individual file. When it finds something, it carefully removes it then goes back to looking. Using xargs lets us group the files together and remove them all at once. This is actually must faster than using the -exec flag with find.

One thought on “Fix Those Pipes

  1. Pingback: Silly Commands - ComputerLamp

Leave a Reply

Your email address will not be published. Required fields are marked *