Bash command to source a file in a different directory?

I have a collection of bash scripts and I want to put some common shell options and variable declarations into a "setup.sh" script which would get sourced at the beginning of each script.
My directory structure is like:

├── includes
│   └── setup.sh
├
└── server_config
    ├── build_server_core.sh
    ├── install_fail2ban.sh

Because the scripts may be run from different computers or environments, I can’t simply use a hard-coded path to the setup.sh

Is there a one-line command to source a script in a different directory to the running script?

Asked By: the_velour_fog

||

First get the directory of the script itself and then use relative paths like that:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source "$DIR/../includes/setup.sh"

For more info about finding the correct directory have a look at https://stackoverflow.com/questions/59895

Answered By: michas
echo "$( echo $(cd ../ && pwd) )/includes/setup.sh"

or

ParDir="$( echo $(cd ../ && pwd) )/includes/setup.sh"

echo $ParDir
Answered By: user256013

As a one-liner: double nesting dirname also gets the parent. (inspired here)

source $( dirname $( dirname "${BASH_SOURCE[0]}" ) )/_helperlib.sh
Answered By: Frank N
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.