Sourcing Other Bash Files with source
The source command reads a file and runs its commands in the current shell, as if they had been typed into the script at that point. Functions and variables that the file defines stay available after source finishes. This is how Bash scripts share code: common functions are kept in a separate file, often called a library, and every script that needs them loads it with source.
source also has a short name, a single dot: . file does exactly the same thing in Bash.
Syntax
source FILENAME [ARGUMENTS...]
. FILENAME [ARGUMENTS...]
FILENAMEis the file to read. It does not need execute permission, because the shell reads it as text instead of starting it as a program.ARGUMENTS, if given, become the positional parameters ($1,$2, ...) while the file runs.- The exit status of
sourceis the status of the last command run from the file, or 1 if the file cannot be read.
A First Library
Here is a small library of text helpers, saved as lib/strings.sh:
# strings.sh - small text helpers, meant to be sourced
to_upper() { printf '%s\n' "${1^^}"; }
trim() {
local s=$1
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
printf '%s\n' "$s"
}
STRINGS_VERSION=1.0
The file only defines two functions and a variable. It has no shebang line and does nothing visible on its own. A script, app.sh, in the folder above lib, loads and uses it:
#!/usr/bin/env bash
source ./lib/strings.sh
echo "using strings.sh $STRINGS_VERSION"
to_upper "gocourse"
echo "[$(trim " padded text ")]"
Running bash app.sh from the folder that holds it:
using strings.sh 1.0
GOCOURSE
[padded text]
After the source line, to_upper, trim and STRINGS_VERSION exist in the script exactly as if their definitions had been written there. trim removes leading and trailing whitespace with the parameter-expansion patterns of lesson 54: ${s%%[![:space:]]*} is the run of leading spaces, which the outer ${s#...} removes, and the second line does the same at the end.
How source Differs from Running a Script
Lesson 28 introduced the difference between running a script and sourcing it. It is the key to understanding source. Running a script, with bash file or ./file, starts a new process. Sourcing it runs the commands in the current process. Consider a file setvars.sh that sets a variable and changes directory:
GREETING="hello"
cd /tmp
Run from a shell whose working directory is /home, then sourced from another such shell:
after running: GREETING=[unset] pwd=/home
after sourcing: GREETING=[hello] pwd=/tmp
When the file was run, the variable and the directory change belonged to the child process and vanished when it ended (lesson 93). When it was sourced, both changes happened in the calling shell and stayed. This is the reason libraries and configuration files are sourced: their whole purpose is to change the current shell by adding functions and variables.
The same property means a sourced file can change anything in the calling script, including variables, the working directory, shell options and traps. A library that runs set -u turns that option on for the script that sources it:
source ./lib/strict.sh # contains: set -u
echo "${undefined_var}"
echo "not reached"
bash: line 1: undefined_var: unbound variable
A well-behaved library defines functions and variables and leaves settings alone, unless changing them is its documented purpose.
The Dot Command
. is the original name of the command and the one defined by POSIX. In Bash, both names work identically:
. ./lib/strings.sh
to_upper dot
DOT
source is easier to read and search for, which is why it is used in this tutorial. Scripts that must run under sh have to use ., as the portability section shows.
Finding the File
How Bash finds the file depends on how the name is written.
A name containing a slash, such as ./lib/strings.sh, lib/strings.sh or /opt/app/lib/strings.sh, is used as a path. A relative path is resolved from the current working directory, not from the folder that holds the script. This is a frequent source of trouble. Running app.sh from a different folder breaks it:
$ cd other && bash ../app.sh
../app.sh: line 2: ./lib/strings.sh: No such file or directory
using strings.sh
../app.sh: line 4: to_upper: command not found
../app.sh: line 5: trim: command not found
[]
The working directory was other, so ./lib/strings.sh pointed to other/lib/strings.sh, which does not exist. Note also that the script kept running after the failed source and failed again at every call to a missing function, ending with status 0.
A name without a slash, such as strings.sh, is first searched for in the directories of PATH (lesson 39). If it is not found there, Bash also looks in the current directory, but only in its normal mode; in POSIX mode (bash --posix) it does not, and the failure stops the shell:
$ PATH="$PWD/bin:$PATH" bash -c 'source pathlib.sh && to_upper "found via PATH"'
FOUND VIA PATH
$ cd lib && bash -c 'source strings.sh && to_upper "found in current directory"'
FOUND IN CURRENT DIRECTORY
$ cd lib && bash --posix -c 'source strings.sh; echo "posix status $?"'
bash: line 1: source: strings.sh: file not found
Because the result depends on PATH and on the working directory, always give source a path with a slash.
Sourcing Relative to the Script's Own Folder
The reliable way to load a library that sits next to the script is to work out the script's folder and build the path from it:
#!/usr/bin/env bash
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
source "$SCRIPT_DIR/lib/strings.sh"
to_upper "works from anywhere"
Run from the unrelated folder other as bash ../app2.sh:
WORKS FROM ANYWHERE
Here is how the first line works, from the inside out:
${BASH_SOURCE[0]}is the path of the file being run, as it was given (../app2.shhere).dirnameremoves the last part, leaving the folder (..).cd -- "..." && pwdchanges into that folder inside the command substitution's subshell and prints its absolute path. The--protects against folder names that begin with a dash.- The result is stored in
SCRIPT_DIR, and thecdhas no effect on the script, because it happened in a subshell (lesson 91).
The library path is now absolute and independent of where the user runs the script from.
BASH_SOURCE and $0 Inside a Sourced File
Inside a sourced file, $0 still holds the name of the script that was started, while ${BASH_SOURCE[0]} holds the path of the file that is being read right now:
# lib/where.sh
echo "\$0=$0 BASH_SOURCE=${BASH_SOURCE[0]}"
Sourced from w.sh with source ./lib/where.sh, and run as bash w.sh:
$0=w.sh BASH_SOURCE=./lib/where.sh
A library should use BASH_SOURCE to find its own location, for example to load further files that sit next to it. Lesson 94 used the comparison of the two values to run main only when a file is executed directly, not when it is sourced.
Passing Arguments to a Sourced File
Extra words after the file name become the positional parameters while the file runs. The script's own parameters come back afterward. Without extra words, the file sees the caller's parameters:
# lib/args.sh
echo "inside args.sh: \$#=$# \$1=[$1]"
set -- main1 main2
source ./lib/args.sh x y z
echo "back in script: \$#=$# \$1=[$1]"
source ./lib/args.sh
inside args.sh: $#=3 $1=[x]
back in script: $#=2 $1=[main1]
inside args.sh: $#=2 $1=[main1]
set -- (lesson 44) gave the script two parameters. The first source passed three arguments, which the file saw as $1 to $3. After it finished, the script's own two parameters were back. The second source passed none, so the file saw the script's parameters.
Handling a Missing File
If the file cannot be found or read, source prints an error and returns status 1:
source ./lib/nothere.sh
echo "status of source: $?"
if ! source ./lib/nothere.sh 2>/dev/null; then
echo "could not load library" >&2
fi
miss.sh: line 1: ./lib/nothere.sh: No such file or directory
status of source: 1
could not load library
A script that cannot work without its library should stop at this point instead of continuing with missing functions, as the broken app.sh above did. A common form is a single line at the top of the script:
source "$SCRIPT_DIR/lib/strings.sh" || { echo "cannot load strings.sh" >&2; exit 1; }
return and exit in a Sourced File
return works at the top level of a sourced file. It stops reading the file early, and its number becomes the status of the source command (lesson 90). exit, in contrast, ends the whole shell that is doing the sourcing, because the file runs in that shell:
# lib/early.sh
echo "early.sh: before return"
return 3
echo "early.sh: never printed"
# lib/quit.sh
echo "quit.sh: calling exit"
exit 4
source ./lib/early.sh
echo "source returned $?"
source ./lib/quit.sh
echo "never printed"
early.sh: before return
source returned 3
quit.sh: calling exit
The script ended with status 4, and its last line never ran. If you source a file containing exit into your interactive terminal, the terminal session itself closes. Libraries should use return, and leave the decision to stop to the script that loaded them.
Loading a Library Only Once
When several libraries depend on each other, the same file can end up sourced more than once. Usually that is harmless, since functions are simply defined again, but a file that sets up counters or prints messages may misbehave. An include guard at the top of the library makes the second and later loads return immediately:
# lib/once.sh
[[ -n ${_ONCE_LOADED:-} ]] && return 0
_ONCE_LOADED=1
echo "once.sh loaded"
source ./lib/once.sh
source ./lib/once.sh
source ./lib/once.sh
echo done
once.sh loaded
done
The first load sets the guard variable. Every later load finds it set and returns before doing anything. The leading underscore and the file-specific name keep the guard variable from clashing with the variables of scripts that use the library.
Configuration Files
Because a sourced file is ordinary Bash, a simple configuration file can be a list of variable assignments:
# app.conf
PORT=8080
LOG_DIR="/var/log/myapp"
source ./app.conf
echo "port=$PORT log=$LOG_DIR"
port=8080 log=/var/log/myapp
This is convenient, and it is how many system files, such as ~/.bashrc (lesson 146) and the files in /etc/default on Debian and Ubuntu, are loaded. It also carries a risk: sourcing runs the file. Any command written into it, not only assignments, executes with the permissions of your script. Only source files that you control and that other users cannot modify. Lessons 154 to 157 cover the security side, including safer ways to read settings from files that are not fully trusted.
Organizing Code into Libraries
With source, the structure from lesson 94 extends across files:
myproject/
├── backup.sh # main script: settings, main(), main "$@"
├── report.sh # another main script
└── lib/
├── log.sh # log(), die()
├── strings.sh # to_upper(), trim()
└── files.sh # functions for checking paths
Each main script computes SCRIPT_DIR, sources the libraries it needs, and then runs its own main. Each library defines functions with local variables, sets as few global names as possible, uses return rather than exit, and has an include guard if it might be loaded twice. Lesson 96 builds a set of reusable utility functions in this style.
Portability
The dot command is part of POSIX and works in Dash; the name source does not:
$ dash -c 'source ./lib/args.sh'
dash: 1: source: not found
The status was 127, the code for a command that does not exist. Dash also differs in how it finds a name without a slash: . strings.sh searched only PATH, did not look in the current directory, printed dash: 1: .: strings.sh: not found, and stopped the shell. Passing arguments after the file name is a Bash feature (Dash ignored x y z in . ./lib/args.sh x y z, and the file saw the caller's parameters). BASH_SOURCE and the [[ ]] test in the include guard are Bash-only too (when Dash sourced once.sh, it reported [[: not found and loaded the file anyway). In a script that must run under sh, use . ./path/file, and find the script's folder from $0 instead of BASH_SOURCE (lessons 188 and 189).