Notes

Bash Scripts - Load/Read/Include Settings from Another File

Edit on GitHub


Bash Scripting

To include a script into another script, we use the source command. In it’s simplest form, the command is this:

1source incl.sh

Here’s an example. Our keys.cfg file has this:

1AWSAccessKeyId="AKIAIKRGQQKRGQQKRGQQ"
2AWSSecretKey="UNYDSEUNYDSEUNYDSEmwMeIdQ6KRGQQv7dBdzDSE"

While our script.sh has this:

1#!/bin/bash 
2
3#Directory the script is in (for later use)
4SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
5
6# Load the backup settings
7source "${SCRIPTDIR}"/keys.cfg

In our script.sh file we have sourced the file keys.cfg which contains configuration settings which we can now use.

If you attempt to execute that shell script from a location other than the one where your script is, it can’t find the include unless it’s in your path. As a workaround we have defined SCRIPTDIR and made the scripts relative to one another.

If the file you are including is in the same directory you can use dirname $0:

1#!/bin/bash
2source $(dirname $0)/incl.sh
3echo "The main script"

An alternative to:

1scriptPath=$(dirname $0)

is:

1scriptPath=${0%/*}

.. the advantage being not having the dependence on dirname, which is not a built-in command (and not always available in emulators)

Resources