Piping output to cut
The first line:
echo $(ps | grep $PPID) | cut -d" " -f4
says:
- Execute
ps | grep $PPID
in a sub-shell Return the output - which will be something like this:
3559 pts/1 00:00:00 bash
and then use that output as the first parameter of echo - which, in practice, means just echo the output
- Then run
cut -d" " -f4
on that - which gives you the command name in this case
The second command:
echo ps | grep $PPID | cut -d" " -f4
says:
- Echo string
ps
- Grep that string for
$PPID
- this will never return anything, as$PPID
contains a number, so it will never beps
. Thus, grep returns nothing - Execute
cut -d" " -f4
with input of the previous command - which is nothing, so you get nothing
The reason is that
echo ps
just prints out the string ps
; it doesn't run the program ps
. The corrected version of your command would be:
ps | grep $PPID | cut -d" " -f4
Edited to add: paxdiablo points out that ps | grep $PPID
includes a lot of whitespace that will get collapsed by echo $(ps | grep $PPID)
(since the result of $(...)
, when it's not in double-quotes, is split by whitespace into separate arguments, and then echo
outputs all of its arguments separated by spaces). To address this, you can use tr
to "squeeze" repeated spaces:
ps | grep $PPID | tr -s ' ' | cut -d' ' -f5
or you can just stick with what you had to begin with. :-)