Unix separate multiple commands which has '&' (execute in background) in the end

6,740

Solution 1

Well the ";" makes the shell wait for the command to finish and then continues with the next command.

The "&" will send any process directly into the background and continues with the next command - no matter if the first command finished or is still running.

So "&;" will not work like you expect.

But actually I'm unsure what you expect.

Try this in your shell:

sleep 2 && echo 1 & echo 2 & sleep 3 && echo 3

it will output: 2 1 3

Now compare it with

sleep 2 ; echo 1 & echo 2 & sleep 3 ; echo 3

which will output 1 2 3

Regards.

Solution 2

command1 & command2 Will execute command1, send the process to the background, and immediately begin executing command2, even if command1 has not completed.

command1 ; command2 Will execute command1 and then execute command2 once command1 finishes, regardless of whether command1 exited successfully.

command1 && command2 will only execute command2 once command1 has completed execution successfully. If command1 fails, command2 will not execute.

(...also, for completeness...)

command1 || command2 will only execute command2 if command1 fails (exits with a non-zero exit code.)

Share:
6,740

Related videos on Youtube

Stan
Author by

Stan

Updated on September 17, 2022

Comments

  • Stan
    Stan over 1 year

    To separate regular commands in Unix is to put semicolon in the end like this:

    cd /path/to/file;./someExecutable;
    

    But it seems not working for commands like this:

    ./myProgram1 > /dev/null &
    ./myProgram2 > /dev/null &
    =>./myProgram1 > /dev/null &;./myProgram2 > /dev/null &;
    

    Is there any way separate these kind of commands?

    Also, if are below 2 cases are equivalent if I copy paste to command prompt? Thanks.

    cd /path/to/file;./someExecutable;
    
    cd /path/to/file;
    ./someExecutable;
    
  • Stan
    Stan over 13 years
    So if I want run 2 commands at the same time in the background. It should be ./myProgram1 > /dev/null & ./myProgram1 > /dev/null & right?
  • gWaldo
    gWaldo over 13 years
    No problem. Hope it helps! Though I'm not sure if it actually answers your original question.
  • Jan.
    Jan. over 13 years
    Yes. But actually it's not EXACTLY happening in the same nano-second :P