According to bash man pages and other online sources, the source command and dot should behave in exactly the same way when sourcing an existing script, but that is not what I observe. Consider this following script which echoes a statement indicating whether a variable is set.
#! /bin/bash
if [[ -v MY_VAR ]]; then
echo "source-test.bash already sourced"
return
fi
export MY_VAR=YES
Here are the results of executing it.
echo $MY_VAR
source source-test.bash
source source-test.bash
source-test.bash already sourced <---- echoed from the script as expected
. source-test.bash
/home/foobar/bin <--- Why is it printing the current directory instead of echoing the output message?
Expected Result After the first time the script is sourced, I expected the string "source-test.bash already sourced" to be echoed regardless of whether I use source or the dot or source command to source the script. Why is the home directory being echoed when I use the dot instead of source?
1 Answer 1
Evidently, I copied some things from a coworker's bash profile with some useful aliases and the period was aliased to pwd. I never noticed that subtle alias definition. In the past I've used the source command, and only after I attempted to use the dot instead of the source command did I realize that this alias existed.
In the .bashrc there was
alias .='pwd'
One of the commenters suggested that I run the following command to determine if the . was aliased to something. This is a good trick that will work in other situations when a command isn't working as you'd expect. Sometimes when an alias is created you might use a combination of letters or a letter that you didn't realize at the time conflicted with an actual command or program name.
type -a .
This is what led me to solve the issue by removing the alias from the .bashrc file.
.:.() { echo ~ ; }.