bash: start multiple chained commands in background
I haven't tested this but how about
print `(touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;) &`;
The parentheses mean execute in a subshell but that shouldn't hurt.
Another way is to use the following syntax:
{ command1; command2; command3; } &
wait
Note that the &
goes at the end of the command group, not after each command. The semicolon after the final command is necessary, as are the space after the first bracket and before the final bracket. The wait
at the end ensures that the parent process is not killed before the spawned child process (the command group) ends.
You can also do fancy stuff like redirecting stderr
and stdout
:
{ command1; command2; command3; } 2>&2 1>&1 &
Your example would look like:
forloop() {
{ touch .file1.lock; cp bigfile1 /destination; rm .file1.lock; } &
}
# ... do some other concurrent stuff
wait # wait for childs to end