Using Piping

The goal of piping is to execute a command and send the output of that command to the next command so this next command can do something with it. For instance, if the output of a command doesn't fit on the screen, the command can be piped to less, which allows you to browse the output of the first command screen by screen. This is, for example, useful when working with ls -lR. This command normally displays a list of files where all properties of the file are displayed and files in all subdirectories of the current directory are displayed. You would use ls -lR | less to send the output from the first command to the second command.

Another useful command you can use in a pipe construction is grep. You can use this command as a filter to filter out information that you want to see. Imagine, for example, that you want to check whether a user with the name julie exists in the user database /etc/passwd.

One solution is to open the file with a viewer such as cat or less and next browse the content of the file to check whether the string you are looking for is present in the file. That is a lot of work, however; a much easier solution is to pipe the content of the file to the filter grep that would filter out all lines that contain the string that is mentioned as an argument of grep. This command would look like cat /etc/passwd | grep julie:the first part of the pipe dumps the complete content of /etc/passwd on the screen, and the second part of the command filters out only those lines where the text julie is present. Notice that grep julie /etc/passwd would do the same thing.

Was this article helpful?

0 0

Post a comment