Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 20 down vote accepted

cp 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; } &
share|improve this answer
7  
Ùnder bash, { ... ; } & 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. –  F. Hauri Aug 26 '13 at 16:34

you can put it into parantheses like (cp a b && mv b c && rm a )& to include the whole chain.

share|improve this answer
2  
And importantly this makes it clear that the entire chain is backgrounded, even to someone who might not know the rules of how operators are bounded –  jackweirdy Aug 26 '13 at 15:49
2  
Look at my comment to @Gilles's answer, I think { ... ; } is a prefereable form (way). –  F. Hauri Aug 26 '13 at 16:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.