What is the 'dot space filename' command doing in bash?

The . ("dot") command is a synonym/shortcut for the shell's built-in source command.

It causes the named shell script to be read in and executed within the current shell context (rather than a subshell). This allows the sourced script to modify the environment of the calling shell, such as setting variables and defining shell functions and aliases.


While the two existing answers are already excellent, I feel the example where the effect is the most "noticeable" so to say, is missing.

Say I have a file script.sh with the following contents:

cd dir

If I would run this script normally (sh script.sh), I'd see this:

olle@OMK2-SERVER:~$ sh script.sh
olle@OMK2-SERVER:~$

But if I where to source the script (. script.sh), I'd end up with this:

olle@OMK2-SERVER:~$ . script.sh
olle@OMK2-SERVER:~/dir$

Notice how in the second case the working directory of our main shell has changed!

This is because (as pointed out in the other answers) the first example runs in its own subshell (the sh process we start with the sh-command, this could have been basically any shell, bash, dash, you name it), it changes directory there, does nothing and closes. While the second example runs in our main shell, and thus changes directory there!


Here is an example.

Script file: mytest.sh

cat mytest.sh

#!/bin/bash

myvar=1
mystring="Hello World"

if you try to print any of the above variables you will get nothing

echo $myvar

but if you do

. mytest.sh

or

source mytest.sh

and then

echo $myvar

it will print 1

Just a visual answer of what Spiff wrote