The likely most important difference would be if the directory that the script is in has a space in it. In that case, the first line, the one without the double-quotes, would fail. This would be the result of "word splitting" which bash does on unquoted strings.
Suppose that the result of dirname ${BASH_SOURCE[0]}
is /home/j r/bin
. Consider the line without quotes:
source $(dirname ${BASH_SOURCE[0]})/script.sh
In this case, bash will see the command:
source /home/j r/bin/script.sh
After word splitting, the source
command sees a script name, /home/j
and an argument to the script, r/bin/script.sh
. Very likely, there is no script by that name and bash will return the error message:
bash: /bin/j: No such file or directory
Now consider what happens with double quotes:
source "$(dirname ${BASH_SOURCE[0]})/script.sh"
In this case, the source command will look for a script named /home/j r/bin/script.sh
and try to source it.
For completeness, let's consider single-quotes:
source '$(dirname ${BASH_SOURCE[0]})/script.sh'
In this case, unlike the previous two, dirname
is never executed. The source command will try to source a command with the literal name $(dirname ${BASH_SOURCE[0]})/script.sh
. There is likely no such file and bash will emit an error message.
How bash treats strings in double quotes is described in full detail in man bash
:
Enclosing characters in double quotes preserves the literal value of
all characters within the quotes, with the exception of $, `, \, and,
when history expansion is enabled, !. The characters $ and ` retain
their special meaning within double quotes. The backslash retains its
special meaning only when followed by one of the following characters:
$, `, ", \, or <newline>. A double quote may be quoted within double
quotes by preceding it with a backslash. If enabled, history expansion
will be performed unless an ! appearing in double quotes is escaped
using a backslash. The backslash preceding the ! is not removed.