Search code examples
linuxbashshellputtyps

Linux Command - 'ps'


My goal was to found the process with highes PID(yes I know can just do ps -ef|tail -n 1, but I want to find the PID first and then find the process), so I used the following command the find the process with the higest PID: ps -ef|cut -d " " -f 6|sort|tail -n 1 and then I find ps -p that gets the highest PID and output the matching process(which works when I copy the PID manually) but for some reason when I put '|' between them it says syntax error. can someone point what the problem is? addtionally if you have better way to this thing post it.

Tnx, Dean

ps, the full command that doesn't work is: ps -ef|cut -d " " -f 6|sort|tail -n 1|ps -p.


Solution

  • There is a difference between providing an argument for a program and writing to a program's standard input, which you are doing.

    In the first case, the program reads the list of arguments as an array of strings, which can be interpreted by the program. In the second case, the program essentially reads from a special file and processes its contents. Everything you put after the program name are arguments. ps expects many possible arguments, for example -p and a PID of a process. In your command, you don't provide a PID as an argument, rather write to stdin of ps, which it ignores.

    But you can use xargs, which reads its standard input and uses it as arguments to a command:

    ps -ef | cut -d " " -f 6 | sort | tail -n1 | xargs ps -p
    

    This is what xargs does (from man):

    xargs - build and execute command lines from standard input
    

    Or you can use command substitution, as janos shows. In this case, the shell evaluates the expression inside $() as a command and puts its output instead. So, after the expansion occurs, your command looks like ps -p 12345.

    man bash:

    Command Substitution
       Command substitution allows the output of a command to replace the com‐
       mand name.  There are two forms:
    
              $(command)
       or
              `command`
    
       Bash performs the expansion by executing command and replacing the com‐
       mand substitution with the standard output of  the  command,  with  any
       trailing newlines deleted.  Embedded newlines are not deleted, but they
       may be removed during word splitting.  The command  substitution  $(cat
       file) can be replaced by the equivalent but faster $(< file).