'Fish shell how to get the PID of the process started in the background

While in FiSH (Friendly Interactive SHell) I can start a process in the background (something &). However, if I try to retrieve the process id of the process (PID=$!) I get an error from fish:

fish: Unknown command “PID=$!”. Did you mean “set PID $!”? For information on assigning values to variables, see the
help section on the set command by typing “help set”.
PID=$!: command not found

How can I retrieve the PID of the background process?



Solution 1:[1]

Using process expansion, you could write

set PID %1          # if you know it's the first background job
set PID %something  # if you know it's the only "something" running

Note that this feature is removed in fish version 3.

Otherwise, we can use the jobs command

set PID (jobs -l | awk '{print $2}')    # just get the pid
jobs -l | read jobid pid cpu state cmd  # get all the things

Solution 2:[2]

From fish version 3, you can use $last_pid as a replacement for %last to get the PID of the last background job.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Damien Ayers