Skip to content

Instantly share code, notes, and snippets.

@brabect1
Last active January 14, 2016 12:31
Show Gist options
  • Save brabect1/57268f71aea5126fb8dd to your computer and use it in GitHub Desktop.
Save brabect1/57268f71aea5126fb8dd to your computer and use it in GitHub Desktop.
Shows how to run BASH subshell in background (i.e. as a separate process)

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 2nd echo does not get the correct PID.
  • The proper way seems keep the echo with its corresponding sleep in the same subshell, e.g. sleep 1; echo slept; ( sleep 1 & echo "sleeping (sub process PID=${!})" ); ps -ef | grep sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment