Home > front end >  Why is this foreground block executed before the background block if it's written later in the
Why is this foreground block executed before the background block if it's written later in the

Time:03-03

#!/bin/bash

{ echo "1" ;
  sleep 3 ;
  echo "2"
} &
{ echo "a"
  sleep 1
  echo "b"
}

The output is

a
1
b
2

Why? Shouldn't echo "1" be executed immediately? Why the output is not

1
a
b
2

CodePudding user response:

It takes some time to run a new process to execute the background code. Also, the output doesn't have to be the same every time you run the code.

CodePudding user response:

I would say, it could be both outputs. And even any output with only constraints being that a is before 1 and b is before 2:

a 1 b 2, b 2 a 1, a b 1 2, a b 2 1, b a 1 2, b a 2 1.

However, it is likely b could be output before a, because the echo b is evaluated by the script's shell, not by a forked/cloned sub-shell...

  •  Tags:  
  • bash
  • Related