Linux – Piping output to cut

bashlinuxshell

I am trying to get the name of the shell executing a script.

Why does

echo $(ps | grep $PPID) | cut -d" " -f4

work while

echo ps | grep $PPID | cut -d" " -f4

does not?

Best Solution

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. :-)