107

Let's take a little example:

$ cat source.sh
#!/bin/bash
echo "I'm file source-1"

. source-2.sh

And:

$ cat source-2.sh
#!/bin/bash
echo "I'm file source-2"

Now run:

$ ./source.sh
I'm file source-1
I'm file source-2

If I'll change the call of the second file in first:

$ cat source.sh
#!/bin/bash
echo "I'm file source-1"

source source-2.sh

It will have the same effect as using dot.

What is difference between these methods?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
setevoy
  • 4,374
  • 11
  • 50
  • 87
  • i also use `bash source-2.sh` sometimes. but if the script just runs `ls` then using `bash source-2.sh` doesn't show shell text colours like the others, and if the script tries to run a missing file then `bash source-2.sh` doesn't provide suggestions on what it thinks you meant to run. and if the script contains `set -e` and i run it with `. source-2.sh` or `source source-2.sh` then it will run the file and crash with suggestions but also crash the server i'm running it on but does crash the server if i used `bash source-2.sh` instead. but to run `bash source-2.sh`, `bash` needs be installed – Luke Schoen Feb 23 '23 at 14:48

2 Answers2

119

The only difference is in portability.

. is the POSIX-standard command for executing commands from a file; source is a more-readable synonym provided by Bash and some other shells. Bash itself, however, makes no distinction between the two.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 3
    Is it just me or does using `source` in `bash --version` `GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)` produce a different behaviour than `.` in weird cases (such as doing it from a function). -- my experience is that `source` export variables more reliably than `.` -- (also, bash differentiate `.` from `source` when re-reading the code via `declare -f`) – Mathieu CAROFF Apr 09 '21 at 12:51
  • @MathieuCAROFF could you paste a simple script example? I am running the exact same bash version as you – Kajsa Gauza Apr 13 '21 at 11:14
104

There is no difference.

From the manual:

source

source filename

A synonym for . (see Bourne Shell Builtins).
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
devnull
  • 118,548
  • 33
  • 236
  • 227