Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for bash commands to continue before the result of the previous command?

Tags:

bash

When running commands from a bash script, does bash always wait for the previous command to complete, or does it just start the command then go on to the next one?

ie: If you run the following two commands from a bash script is it possible for things to fail?

cp /tmp/a /tmp/b cp /tmp/b /tmp/c 
like image 687
corydoras Avatar asked Mar 07 '10 23:03

corydoras


People also ask

Does bash wait for command to finish before executing next?

The bash WAIT command is used to halt the execution of a script until all background jobs or specified JobID/PIDs terminate successfully and return an expected exit code to trigger the next command that was “waited for.”

Is there continue in bash?

The continue statement is a Bash builtin that alters the flow of script loops. The concept is not unique to Bash and appears in other programming languages. The best way to understand how the Bash continue statement works is through hands-on examples.

How do I continue a new line in bash?

From the bash manual: The backslash character '\' may be used to remove any special meaning for the next character read and for line continuation. thanks.


2 Answers

Yes, if you do nothing else then commands in a bash script are serialized. You can tell bash to run a bunch of commands in parallel, and then wait for them all to finish, but doing something like this:

command1 & command2 & command3 & wait 

The ampersands at the end of each of the first three lines tells bash to run the command in the background. The fourth command, wait, tells bash to wait until all the child processes have exited.

Note that if you do things this way, you'll be unable to get the exit status of the child commands (and set -e won't work), so you won't be able to tell whether they succeeded or failed in the usual way.

The bash manual has more information (search for wait, about two-thirds of the way down).

like image 188
Zach Hirsch Avatar answered Sep 19 '22 23:09

Zach Hirsch


add '&' at the end of a command to run it parallel. However, it is strange because in your case the second command depends on the final result of the first one. Either use sequential commands or copy to b and c from a like this:

cp /tmp/a /tmp/b & cp /tmp/a /tmp/c & 
like image 28
Tareq Sha Avatar answered Sep 17 '22 23:09

Tareq Sha