Obtain script current directory (so that I can do include files without relative paths and run the script from everywhere)

The $0 variable contains the script's path:

$ cat ~/bin/foo.sh
#!/bin/sh
echo $0

$ ./bin/foo.sh
./bin/foo.sh

$ foo.sh
/home/terdon/bin/foo.sh

$ cd ~/bin
$ foo.sh
./foo.sh

As you can see, the output depends on the way it was called, but it always returns the path to the script relative to the way the script was executed. You can, therefore, do:

## Set mydir to the directory containing the script
## The ${var%pattern} format will remove the shortest match of
## pattern from the end of the string. Here, it will remove the
## script's name,. leaving only the directory. 
mydir="${0%/*}"

# config load
source "$mydir"/config.sh

If the directory is in your $PATH, things are even simpler. You can just run source config.sh. By default, source will look for files in directories in $PATH and will source the first one it finds:

$ help source
source: source filename [arguments]
    Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

If you are sure your config.sh is unique or, at least, that it is the first one found in $PATH, you can source it directly. However, I suggest you don't do this and stick to the first method instead. You never know when another config.sh might be in your $PATH.


This method is only useful in a bash script.

Use:

mydir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"

How it works:

BASH_SOURCE is an array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined.

So, with:

cd "$( dirname "${BASH_SOURCE[0]}" )"

you move to the directory where the script is placed.

Then, the output of cd is sent to /dev/null, because sometimes, it prints something to STDOUT. E.g., if your $CDPATH has .

And finally, it executes:

pwd

which gets the current location.

Source:

https://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?page=1&tab=oldest#tab-top


Found the solution:

mydir=$(dirname "$0")

With this the script can be invoked from everywhere without throubles.