What it does
A script normally runs in a new child shell: when it ends, its variables are gone. source FILE (or the short form . FILE) reads the file and runs its lines in your current shell. Variables, aliases, functions and cd changes stay.
Use it to load ~/.bashrc after an edit, to load settings from a file (.env), or to use a library of shell functions in a script.
How to write it
source FILE [ARGUMENTS]
. FILE [ARGUMENTS]Options 2
Most used
Nothing matches this filter.
Examples 10
$ run as a normal user# run as root (or with sudo)
1Load your .bashrc after an edit
source ~/.bashrcNew aliases and variables work at once, without logging out.
2The short form with a dot
. ~/.bashrcExactly the same as
source.3Load variables from a settings file
set -aexports every variable that is set, so programs started later get them.4Use shared functions in a script
cat /usr/local/lib/ops-lib.sh log() { echo "$(date +%F_%T) $*"; } cat deploy.sh #!/bin/bash source /usr/local/lib/ops-lib.sh log "deploy started"One library file, many scripts. Fix a function once.
5Activate a Python virtual environment
source ~/venvs/ansible/bin/activateThe activate script changes PATH in your shell, so it must be sourced, not run.
6Check what a script changes before you trust it
bash -n setup.sh && source setup.shbash -nchecks the syntax without running anything.7Load the environment of a service in a test
Many services read their options from a file in /etc/sysconfig. Load it to test the same settings by hand.
8Pass arguments to the sourced file
source ./set-cluster.sh productionInside the file,
$1isproduction.9Make a change of folder stay
Run as
./goto-logs.sh, thecdwould happen in a child shell and you would not move.10Reload the shell profile for all users after a change (current shell)
source /etc/profileOther users get it at their next login.
Nothing matches this filter.
Watch out
Tips to remember
- Run a script = new child shell.
source= this shell. sourceand.are the same.