Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping output to cut

Tags:

linux

bash

shell

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?

like image 515
ZPS Avatar asked Feb 22 '12 03:02

ZPS


People also ask

What does it mean to pipe output?

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.

What is in cut command?

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.

What does TR D do?

DESCRIPTION Translate, squeeze, and/or delete characters from standard input, writing to standard output.

What is the cut command in bash?

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.


2 Answers

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

like image 144
ruakh Avatar answered Sep 20 '22 15:09

ruakh


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 be ps. Thus, grep returns nothing
  • Execute cut -d" " -f4 with input of the previous command - which is nothing, so you get nothing
like image 22
icyrock.com Avatar answered Sep 20 '22 15:09

icyrock.com