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?
source is a synonym for dot/period '. ' in bash, but not in POSIX sh, so for maximum compatibility use the period. When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes.
To source a script is to run it in the context of the current shell rather than running it in a new shell. For example: . myscript.sh. or: source myscript.sh. (depending on which shell you're running).
Sourcing a script will run the commands in the current shell process. Changes to the environment take effect in the current shell. Executing a script will run the commands in a new shell process.
On the other hand, source is 5 characters longer and is not portable to POSIX-only shells or Bourne whereas . (dot) is, so I never bother using source. That is correct - sourcing a file runs the commands in the current shell and it will affect your current shell environment.
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.
They are equivalent in bash in that they do exactly the same thing. On the other hand, source is 5 characters longer and is not portable to POSIX-only shells or Bourne whereas . (dot) is, so I never bother using source. That is correct - sourcing a file runs the commands in the current shell and it will affect your current shell environment.
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. @MathieuCAROFF could you paste a simple script example?
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.
There is no difference.
From the manual:
source
source filename A synonym for . (see Bourne Shell Builtins).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With