I want to background a command chain like cp a b && mv b c && rm a
.
I have tried doing cp a b && mv b c && rm a &
but this only backgrounds the last process.
How do I background a command chain?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitycp a b && mv b c && rm a &
is correct. &
has lower precedence than &&
. In fact &
has lower precedence than anything other than ;
and newline: &
is in the same syntactic category as ;
, the difference being that ;
runs the command list in the foreground while &
runs it in the background. You can test this for yourself:
$ dash -c 'sleep 2 && echo waited & echo backgrounded'
backgrounded
$ waited
Same with pdksh, ksh93, bash, csh, tcsh.
The exception is zsh, which is weirdly incompatible. This is documented in the manual:
If a sublist is terminated by a
&
,&|
, or&!
, the shell executes the last pipeline in it in the background, and does not wait for it to finish (note the difference from other shells which execute the whole sublist in the background).
Unfortunately, zsh behaves in this way even in sh or ksh compatibility mode. To make sure that the whole command is executed in the background, put braces or parentheses around it. Parentheses create a subshell whereas braces don't, but this is irrelevant (except as a micro-optimization in some shells) since a backgrounded command is in a subshell anyway.
{ cp a b && mv b c && rm a; } &
{ ... ; } &
do a fork at current process level, while ( ... ) &
do a fork from a subshell... The result is same, but there is a subtle difference anyway.
Aug 26, 2013 at 16:34
you can put it into parantheses like (cp a b && mv b c && rm a )&
to include the whole chain.
{ ... ; }
is a prefereable form (way).
Aug 26, 2013 at 16:38