Reputation: 53
I am studying for 'operational Systems' exams at my uni and i am having hard time understanding pipes usage (|). Here is an example i found on internet:
ps -ax | grep Finder
Use the ps command to get a list of processes running on the system, and pass the list to grep to search for lines containing "Finder". (Usually, it'll find two: the Finder, and the processes executing grep Finder.)
What if i first write ps -ax
and at next line grep finder
? wont it have the same result? why i have to pipe them together?
ps: Bigginer at unix shell commands and how it works.
Upvotes: 0
Views: 53
Reputation: 8093
Unix is a file based system. And unless you specify where you want to redirect the output, it will be displayed on screen.
So if you type ps ax
, it will list all the running processes on the screen.
So if you type ps ax
first and then grep
then you will get all the process and then you will get error as grep
expects at least 2 parameters, keyword
and filename
.
So you have to do 2 steps.
ps ax > filename
grep finder filename
This will give you the result.
Pipe |
redirects the output from left side, as a file, to the right side command. So you can merge the 2 steps.
So instead of all above, you can just say, ps ax|grep finder
, which will pass the output of ps ax
as a file to grep
command.
Note than in this way, you didn't specify a file name to grep
directly. Instead you are telling it to use the output of ps ax
as a file
Upvotes: 1
Reputation: 42588
It's all about redirecting input and output.
If you were to type ps -ax > processes
, you would create the file processes
with a list of all the processes. This is redirecting output. All the data shown to the screen is instead written to a file.
If you were to type grep Finder < processes
, you would search the file processes
for the word Finder. This is redirecting input.
Pipe does both. It redirects the output of the command on the left side and redirects the input of the command on the right side.
$ ps -ax | grep Finder
is like
$ ps -ax > temp
$ grep Finder < temp
except all on one line with no temp file to delete.
Upvotes: 3
Reputation: 309
No, the result would not be the same in the two cases you mentioned above. Try it out.
ps -ax
by itself would send its result to the standard output.
grep Finder
by itself would not work at all
pipe creates a unidirectional data channel that can be used for interprocess communication. So, ps -ax | grep finder
, essentially redirects the output of ps -ax
as an input stream into the grep Finder
command, which in turn searches for the string 'Finder' in that stream.
Upvotes: 1