Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last(latest) process pid in linux

I want to get the last/latest process pid in linux.Can anyone suggest me the command to find that ? But I don't know which process has started last.

like image 914
advishnuprasad Avatar asked Dec 08 '22 20:12

advishnuprasad


2 Answers

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] 3009
root@unix ~ % ps aux --sort +start_time | tail -n 4 | awk 'NR==1{print $2 " " $11}'
3009 sleep
root@unix ~ %

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

like image 148
meisterluk Avatar answered Jan 17 '23 09:01

meisterluk


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
like image 24
bougui Avatar answered Jan 17 '23 09:01

bougui