To return the PID (process ID) of the last command in Linux or Unix, you can use the special shell variable $!
.
This variable contains the PID of the last background process started by the current shell. For example, if you run the command sleep 30 &
, the variable $!
will contain the PID of the sleep
process.
You can use this variable to check the status of the last background process or to kill it.
For example, you can use the command echo $!
to print the PID of the last background process, or kill $!
to kill it.
Another way to get the pid of last command is by using pgrep
command
pgrep -f "mycommand"
This command will return the pid of the last command that matches the string “mycommand”
Please note that if the last command was not run in background, the variable $!
will be empty and this method will not work.