0

I have a bash script which contains following command.

docker-compose -f ./local/d-compose.yml build &

Notice that it has & at the end. I understand that this command will be executed in background if executed directly on bash shell prompt. However, I do not understand how it would be handled if this is executed in bash script.

Moreover, how it will make a different if I run script by source <script_name> instead of ./<script_name>?

2
  • 1
    You've tried running it, right? You know the actual behavior? Now, which of your questions remain unanswered in that context? (Or, to restate in terms more pertinent to whether the site's topicality rules are being followed: What's the specific, practical problem that you're trying to solve?) Commented May 15, 2020 at 3:18
  • @AbhishekGupta : When doing this in a script, you likely will at some later time wait for the background task to be finished. This is done using the wait command. Commented May 15, 2020 at 6:57

1 Answer 1

4

The job control instruction & in Unix/Linux asks it to run the instruction as a background job, returning you back a shell command prompt.

Executed in a script run in the foreground, this particular instruction will be run as stated above, i.e. in background mode (in a sub-shell, or not if you use source), while the rest of the script continues to run in sequence in foreground mode.

Example with a bash script of 5 instructions, executed in the foreground (call is not followed by &):

#! /bin/bash

ls a*
ls b*
ls c* &
ls d*
ls e*

In that case, the script would call the first ls, wait for its completion, then call the second ls, wait for its completion, call the third ls with &. Here the OS would put that job in background and immediately return control to the script without waiting for completion. The script would thus immediately continue and call the fourth ls, wait for its completion, and finally call the fifth ls.

So for calls / execution, you'd get

  1. First ls called
  2. First ls executed
  3. Second ls called
  4. Second ls executed
  5. Third ls called
  6. Fourth ls called
  7. Fourth ls executed
  8. Fifth ls called
  9. Fifth ls executed

As for the Third ls, it would finish executing any time after step 5, in effect interspersing its results in between the ones of the fourth or fifth ls calls.

Using source would not change that behaviour, only execute the script in the current shell (using source), or execute the script in a sub-shell (not using source).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.