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?
A pipe is a form of redirection (transfer of standard output to some other destination) that is used in Linux and other Unix-like operating systems to send the output of one command/program/process to another command/program/process for further processing.
The cut command is a command-line utility that allows you to cut out sections of a specified file or piped data and print the result to standard output. The command cuts parts of a line by field, delimiter, byte position, and character.
DESCRIPTION Translate, squeeze, and/or delete characters from standard input, writing to standard output.
The cut command is used to extract the specific portion of text in a file. Many options can be added to the command to exclude unwanted items. It is mandatory to specify an option in the command otherwise it shows an error.
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. :-)
The first line:
echo $(ps | grep $PPID) | cut -d" " -f4
says:
ps | grep $PPID
in a sub-shellReturn 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
cut -d" " -f4
on that - which gives you the command name in this caseThe second command:
echo ps | grep $PPID | cut -d" " -f4
says:
ps
$PPID
- this will never return anything, as $PPID
contains a number, so it will never be ps
. Thus, grep returns nothingcut -d" " -f4
with input of the previous command - which is nothing, so you get nothingIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With