To run a command in background in BASH, one simply adds &
after the command: command &
. The PID of
the spawned backgorund proces is the return code, $!
.
This is fine within a script, but what if you want to run the commands as one liner?
For example
sleep 1
echo slept
sleep 1 &
echo "sleeping (sub process PID=${!})"
ps -ef | grep sleep
as opposed to sleep 1; echo slept; sleep 1 &; echo "sleeping (sub process PID=${!})"; ps -ef | grep sleep
.
Most likely you'll encounter a syntax error bash: syntax error near unexpected token ';'
The solution is as follows (see here):
- Drop
;
after&
. This works but may have unexpected behavior if&&
is used instead of;
to separate individual commands. - Alternatively one may spawn the background process from a sub-shell, e.g.
sleep 1; echo slept; ( sleep 1 & ); echo "sleeping (sub process PID=${!}); ps -ef | grep sleep"
. Unfortunately, the 2ndecho
does not get the correct PID. - The proper way seems keep the
echo
with its correspondingsleep
in the same subshell, e.g.sleep 1; echo slept; ( sleep 1 & echo "sleeping (sub process PID=${!})" ); ps -ef | grep sleep