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

When using bash shell, I sometimes keep environment variables in a text file which I copy/paste the content of, eg exports.txt:

export FOO=bar
export FIZZ=buzz

Someone showed me instead of copy/paste, I could type in the terminal

. exports.txt

which would have the same effect as copy/paste.

What is the mechanism by which this 'dot space filename' command works? It's hard to think of search terms for it.

I want to understand what is happening and the more general details of what this one-liner is doing.

5

3 Answers

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.

2

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

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like