What is the 'dot space filename' command doing in bash?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 What Is The 'Dot Space Filename' Command Doing In Bash?
00:35 Accepted Answer Score 50
00:56 Answer 2 Score 6
01:27 Answer 3 Score 32
02:27 Thank you
--
Full question
https://superuser.com/questions/1136409/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#bash #export
#avk47
ACCEPTED ANSWER
Score 50
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.
ANSWER 2
Score 32
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!
ANSWER 3
Score 6
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