Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does “exec some_cmd &” mean in bash

Tags:

bash

I found a use of exec some_cmd & in this script:

...
exec elixir \
  -pa _build/prod/consolidated \
  --no-halt \
  --erl "+A$THREAD_COUNT" \
  --erl "+K true" \
  --erl "-smp auto" \
  --erl "+scl false" \
  --erl "+spp true" \
  --erl "+swt low" \
  --erl "+sbwt long" \
  --sname $NODE \
  --cookie $COOKIE \
  -S mix run \
    --no-compile \
$@ \
&
...

exec some_cmd replaces the shell with some_cmd. some_cmd & spawns some_cmd as a child process in background. So what happens when combining them?

I gave it a try with bash 3.2 and the result shows that it looks like it spawns a background process:

# script
echo "Shell PID: $$"
exec sh -c 'echo "Child PID: $$"' &
BG_PID=$!
echo "Background process PID: $BG_PID"

# output
Shell PID: 8852
Background process PID: 8853
Child PID: 8853

Though I'm not sure whether it is exactly the same as some_cmd &.

like image 398
uasi Avatar asked Dec 26 '15 06:12

uasi


1 Answers

The exec command has no effect in this case. Normally, exec would prevent bash from forking before calling execve, but in this case bash forks anyway because you said &.

So exec some_cmd & is the same as some_cmd &.

You might use exec with & anyway if you need to use one of the exec flags. Type help exec to see what flags exec supports.

like image 147
rob mayoff Avatar answered Sep 23 '22 15:09

rob mayoff