To return the process ID (PID) of the last command in Linux or Unix, you can use the echo
command and the $!
shell variable. The $!
variable contains the PID of the last command that was run in the background.
Here is an example of how to use the echo
command and the $!
variable to return the PID of the last command:
command & echo $!
Replace command
with the command you want to run. The &
at the end of the command tells the shell to run the command in the background. The echo
command will then print the PID of the command to the console.
Keep in mind that the $!
variable will only contain the PID of the last command that was run in the background. If the command was not run in the background, the $!
variable will not be set, and the echo
command will print an empty line.
You can also use the ps
command to find the PID of a running command. For example, to find the PID of a command with the name command_name
, you can use the following command:
ps aux | grep command_name
This will display a list of processes with the name command_name
, along with their PIDs.
Alternatively, you can use the pgrep
command to find the PID of a running command. For example, to find the PID of a command with the name command_name
, you can use the following command:
pgrep command_name
This will display the PID of the first process with the name command_name
that is found. If multiple processes with the same name are running, you can use the -l
option to display the PIDs of all matching processes:
pgrep -l command_name