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.

This question already has an answer here:

I'm trying to write a command that's a one-line for loop containing a command that uses the & operator to put the command in the background:

for dir in $(ls); do command $dir &; done

Where & tells BASH to run command in the background. Yet BASH returns

bash: syntax error near unexpected token `;'

What's going on here? How can I use & in conjunction with ;? I tried enclosing things in quotes, like do "command $dir &" or do command $dir "&" but those have unexpected results.

share|improve this question
3  
Beware using $(ls) in place of * is generally considered a bad practice. Because of the nature of globbing * will allow you to deal with filenames that contain whitespace, $(ls) will not. Consider a list of files, "one a", "one b", "two". With $(ls) you will iterate "one", "a" "one", "b", "two". With * you will iterate the actual file list. –  TAFKA 'goldilocks' Jan 24 at 22:49
add comment

marked as duplicate by Stephane Chazelas, Gilles, slm, jasonwryan, strugee Jan 25 at 3:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 3 down vote accepted

You don't use the ; with '&', the '&' on its own is enough to finish the command. I believe there is currently no mention of this behaviour in the manual. Your loop would simply be:

for dir in $(ls); do command $dir & done

Additionally, you should consider using a glob instead of $(ls) which will fail if the filename contains whitespace. You can set nullglob to prevent dir being a * if there are no files:

shopt -s nullglob
for dir in *; do command $dir & done
share|improve this answer
    
There's no mention because ;, &, &&, ||, and \n are all command separators, some of which have different meanings than others. –  DopeGhoti Jan 24 at 22:38
    
+1 for dir in $(ls); do command $dir ;; done will throw the same error, as will for f in $(ls); do echo $f |;done etc. –  TAFKA 'goldilocks' Jan 24 at 22:39
add comment

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