I know I can run a program in the background using &.

command &

However, I want to run multiple commands, and cd into a different directory while they are running.
The multiple commands will still rely on the directory I was previously in.

I've tried the following, but it only runs the last command in the background:

command1 && command2 &

Doing this gives a parse error:

command1 & && command2 & 

It's important that command1 finishes before command2,
so I don't think the following would guarantee that:

 command1 &; command2 &;  

I'm not tied to any specific shell.

  • Note that ; isn't needed after &, it can separate commands itself: command1 & command2. – choroba May 4 '16 at 14:59
  • @choroba Not just not needed, it's a syntax error (in bash and most other shells): there needs to be a command before ; – Gilles 'SO- stop being evil' May 4 '16 at 22:59
  • If you need to do that in a bash script, use the method suggested here: stackoverflow.com/a/62832235/1423806 – Bemipefe Jul 10 '20 at 10:25

(command1; command2)& - should do it, works in bash.

This creates a subshell (the two parenthesis) and runs the whole subshell in the background.

  • 4
    Or { command1; command2; } & — running a command in the background already creates a subshell so using (…) instead of { … } is redundant. – Gilles 'SO- stop being evil' May 4 '16 at 22:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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