tags:

views:

140

answers:

6

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
+1  A: 

In general, unless explicitly sent to the background or forking themselves off as a daemon, commands in a shell script are serialized.

Ignacio Vazquez-Abrams
+1  A: 

They wait until the previous one is finished. However, you can write 2 scripts and run them in separate processes, so they can be executed simultaneously. It's a wild guess, really, but I think you'll get an access error if a process tries to write in a file that's being read by another process.

mingos
A: 

I think what you want is the concept of a subshell. Here's one reference I just googled: http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/subshells.html

Devin Ceartas
+1  A: 

Unless you explicitly tell bash to start a process in the background, it will wait until the process exits. So if you write this:

foo args &

bash will continue without waiting for foo to exit. But if you don't explicitly put the process in the background, bash will wait for it to exit.

Technically, a process can effectively put itself in the background by forking a child and then exiting. But since that technique is used primarily by long-lived processes, this shouldn't affect you.

R Samuel Klatchko
+4  A: 

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 &
tareqHs
+1: Good point about the question copying to /tmp/b and then copying /tmp/b to /tmp/c!
Jonathan Leffler
It was just an artificial example (:
corydoras
that's clear, my point was to be careful when parallelizing dependent commands :)
tareqHs
+8  A: 

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).

Zach Hirsch