Get the last(latest) process pid in linux Get the last(latest) process pid in linux unix unix

Get the last(latest) process pid in linux


If you want the process ID of the most recently executed background command you can use the ! variable. For example:

 > gvim text.txt & > echo $! 2842


Update: Thanks to William for the hint about awk.
Pre-condition: The process has still to be running.

I am not an UNIX expert, but I thought about the following approach:

ps aux --sort +start_time | tail -n 4 | awk 'NR==1{print $2}'

ps will list all processes and we are going to sort them by start_time. Afterwards we are going to take the fourth from the last line [0] of the output and awk will return the pid found in the second field.

root@unix ~ % sleep 10 &[1] 3009root@unix ~ % ps aux --sort +start_time | tail -n 4 | awk 'NR==1{print $2 " " $11}'3009 sleeproot@unix ~ %

[0] The fourth line because there are three piped commands in my commandline.


Get PID:

#!/bin/bashmy-app & echo $!

Save PID in variable:

#!/bin/bashmy-app & export APP_PID=$!

Save all instances PID in text file:

#!/bin/bashmy-app & echo $! >>/tmp/my-app.pid

Save output, errors and PID in separated files:

#!/bin/bashmy-app >/tmp/my-app.log 2>/tmp/my-app.error.log & echo $! >>/tmp/my-app.pidecho "my-app PID's: $(cat /tmp/my-app.pid)"