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=buzzSomeone showed me instead of copy/paste, I could type in the terminal
. exports.txtwhich 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.
53 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.
2While 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 dirIf 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 $myvarbut if you do
. mytest.shor
source mytest.shand then
echo $myvarit will print 1
Just a visual answer of what Spiff wrote
2