How and When to Use the Dot Command in Bash?
First of, the dot command (
.) is not to be confused with a dot file or a relative path notation. For example, the
~/.ssh folder is a hidden folder using the dot file notation, you will need to use
ls -a to see that folder. And
./my-script.sh is a relative path to the script named "my-script.sh" in the current folder. Using the Dot command would be as such:
The dot command (
.), aka full stop or period, is a command used to evaluate commands in the current execution context. In Bash, the
source command is synonym to the dot command (
.) and you can also pass parameters to the command, beware, this deviate from the POSIX specification.
.: . filename [arguments] Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. Exit Status: Returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read.
👉 Unless you provide an exact path to the filename, Bash will use the
$PATHentries to find the file to evaluate.
How to use the Dot Command in Bash?
When you run an executable script as
./my-script.sh, the commands are run in a new subshell, while when run as
. my-script.sh the current shell context will be used. Generally, your current context is your terminal window. This mean that the dot command will apply changes to your current shell. Let's look at the simple example below.
#!/usr/bin/env bash export A="hello world" echo $A
When run as an executable using
A variable is not exported in your current shell and would just return an empty result.
$ ./test.sh hello world $ echo $A
When run the same script with the dot command using
. my-script.sh, your current shell context will be changed.
$ . test.sh hello world $ echo $A hello world
When to use the Dot Command in Bash?
The most obvious use case for using the dot command is when you want to change your current context by setting new variables or changing some existing one. You may also have a script that expect to change your current directory by using
cd. It may also be convenient when trying to run a script that doesn't have the execute (