Table of Contents

source

Possible test scenario:

  1. call from another directory by full path /home/user/bin/myscripth.sh
  2. add /home/user/bin to PATH and then call from another directory by myscript.sh
  3. create symlink to script and call using symlink. Check for relative and absolute symlinks.
  4. it should work also if it is sourced source or .

The best is to create setup/installer script which hardcode path to one shared script.

Take note of possible problems:

Universal approach

This handles executed, sourced, symlinked and sourced-symlinked files, and always returns an absolute path to the real directory.

src="${BASH_SOURCE[0]}"
while [ -L "$src" ]; do
  dir=$(CDPATH= cd -P -- "$(dirname -- "$src")" && pwd)
  src=$(readlink "$src")
  case $src in /*) ;; *) src=$dir/$src ;; esac   # relative link target
done
DIR=$(CDPATH= cd -P -- "$(dirname -- "$src")" && pwd)

Simple and universal.

readlink -f follows the whole symlink chain itself (nested links, relative targets, symlinked directories), so no loop is needed. It works on any Linux (GNU coreutils, BusyBox) and on macOS 12.3+. It also works for sourced files, because BASH_SOURCE[0] is the sourced file’s own path, which covers the sourced-and-symlinked case.

src="${BASH_SOURCE[0]}"
DIR=$(cd -- "$(dirname -- "$(readlink -f -- "$src")")" && pwd)

NOTE: Not working well in all scenarios!

#!/bin/sh
MY_DIR=$(dirname $(readlink -f $0))
$MY_DIR/other_script.sh
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# Works correctly if script is sourced from another one
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cur_file="${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"
cur_dir="$(dirname "${cur_file}")"

''`BASH_SOURCE'

   An array variable whose members are the source filenames where the
   corresponding shell function names in the `FUNCNAME' array
   variable are defined.  The shell function `${FUNCNAME[$i]}' is
   defined in the file `${BASH_SOURCE[$i]}' and called from
   `${BASH_SOURCE[$i+1]}'

''