Sourcing Other Bash Files with source

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 95 of 205

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...]
  • FILENAME is 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 source is 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:

  1. ${BASH_SOURCE[0]} is the path of the file being run, as it was given (../app2.sh here).
  2. dirname removes the last part, leaving the folder (..).
  3. cd -- "..." && pwd changes into that folder inside the command substitution's subshell and prints its absolute path. The -- protects against folder names that begin with a dash.
  4. The result is stored in SCRIPT_DIR, and the cd has 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).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Sourcing Other Bash Files with source and get answers drawn from it.

Signed-in readers only.