Consecutive commands

Am I correct to assume that when ; joins two commands on a line, Bash always waits until the first command has exited before executing the second command?
And similarly, in a shell script containing two different commands on different lines, Bash always waits until the command on the first line has exited before executing the command on the second line?

If this is the case, is there a way to execute two commands in one line or in a script, so that the second command doesn’t wait until the first command has finished?

Also, are different lines in a shell script equivalent to separate lines joined by ; or &&?

Asked By: EmmaV


You’re correct, commands in scripts are executed sequentially by default.

You can run a command in the background by suffixing it with & (a single ampersand).

Commands on separate lines are equivalent to commands joined with ; by default. If you tell your shell to abort on non-zero exit codes (set -e), then the script will execute as though all the commands were joined with &&.

Answered By: Stephen Kitt

To answer your second question, you can use & to launch a command in the background and continue with the script without waiting for it to finish.

commandA & commandB

If you run this at an interactive terminal (instead of a script), you can use fg to bring the backgrounded command back into focus, or jobs to see a list of background tasks.

Answered By: rmelcer

In the simplest scenario, when you have full control over the previous process you can chain the next command with firstCommand && secondCommand as already mentioned in other answers. The syntaxis implies that firstCommand assumes responsibility for returning a correct exit code (0 on success and non-zero on failure), and that secondCommand will only run if firstCommand exited successfully.

When you do not have control over firstCommand or when it’s already running, or when firstCommand does not return sane exit codes on success/failure then you can poll for running processes every N seconds and start secondCommand after the first one exits:

while true ; do pgrep firstCommand && echo 'Still running...' || secondCommand ; sleep 1 ; done

❗️ CAVEAT: secondCommand will run even if firstCommand finished with a non-zero exit status.

Also see:

Answered By: ccpizza

As others said, you have to add & sign at the end of command that should run in background.

If you want a script to complete all tasks simultaneously and then exit, just add "wait" command at the end of the script. In such scenario, bash is waiting for all commands to finish until it goes any further.

Answered By: Jacek
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.