Search code examples
linuxbashshell

exec keyword on a background command?


Normally, in a bash script, exec replaces the bash process, and the rest of the script is ignored:

#!/bin/bash
exec command1
command2        # will not execute

However, if we add & after the exec line, it will continue to run:

#!/bin/bash
exec command1 &
command2        # will execute

It seems totally equivalent to a non-exec script which simply puts command1 to background:

#!/bin/bash
command1 &
command2        # will execute

Is it really no difference between using and not using exec on a background command?

Will it be faster or slower if using exec?


Solution

  • I answer you with a small example.

    main.sh

    #!/bin/bash
    
    echo "Main PID = $BASHPID"
    exec ./exec_background.sh &
    exec ./exec.sh
    

    exec.sh

    #!/bin/bash
    
    echo "Exec PID = $BASHPID"
    

    exec_background.sh

    #!/bin/bash
    
    echo "Exec Background PID = $BASHPID"
    

    Running it you get, for example:

    Main PID = 9547
    Exec PID = 9547
    Exec Background PID = 9548
    

    As you can see the exec command reports the same PID of the main bash instance, instead the background exec command spawns a new bash shell (by the different PID).

    In conclusion, the background exec commmand behaves like a standard background execution command without the exec keyword.

    I think that the execution time of the two variants is the same, both have to spawn a new bash shell.