Executing a script with dot vs source in Bash

What are the differences between source scriptname.sh, . scriptname.sh and ./scriptname.sh when executing scripts?

Running a program in Bash

Executing a script is simple in Bash and many other shells.

1
scriptname.sh

OR

1
./scriptname.sh

The shell commands above will execute the scriptname.sh script as a separate program from the command line. It may be any type of script.

Sourcing a script in Bash

When a file is sourced, it runs in the current user’s shell as if the commands were typed out.

1
. scriptname.sh

OR

1
source scriptname.sh

The most common use case is when scripts export environment variables.

1
export ENV_VAR=test
1
2
source test.sh
echo $ENV_VAR

Output:

1
test