4

From the BASH pages:

When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script.

But what happens if I run

. myscript &

Does it run as a subshell in this case? What's the difference between . myscript & and ./myscript &?

durron597
  • 31,968
  • 17
  • 99
  • 158
Pithikos
  • 18,827
  • 15
  • 113
  • 136

1 Answers1

5

Yes - you can easily test this:

Source file:

echo "Source File"
echo "Source PID - $BASHPID"
MYVAR=someval

Execute file:

. source 

echo "Exec PID -$BASHPID"
echo $MYVAR
echo done

Output:

Source File
Source PID - 34893
Exec PID - 34893
someval
done

If you use the & in the . source of the execute file, the execution order is different, and so are the PIDs associated with the process, and you can see the MYVAR variable set in the source file is not printed:

Exec PID - 34931

done
Source File
Source PID - 34932
arco444
  • 22,002
  • 12
  • 63
  • 67
  • 1
    So what should I do if I wanted to source a file in the background? For my use case, I have a couple of slow processes in my `zshrc`, so I tried putting an `&` at the end of those slow lines. Hoping that this would parallelize the shell startup. It ended up helping a bunch, but I noticed none of the changes had any affect! What is an effective way to make my `zshrc` startup asynchronous? – Max Coplan Dec 30 '19 at 22:09