Refer to a file under the same directory of a script found in $PATH

These should work the same, as long as there are no symlinks (in the path expansion or the script itself):

  • MYDIR="$(dirname "$(realpath "$0")")"

  • MYDIR="$(dirname "$(which "$0")")"

  • A two step version of any of the above:

    MYSELF="$(realpath "$0")"

    MYDIR="${MYSELF%/*}"

If there is a symlink on the way to your script, then which will provide an answer not including resolution of that link. If realpath is not installed by default on your system, you can find it here.

[EDIT]: As it seems that realpath has no advantage over readlink -f suggested by Caleb, it is probably better to use the latter. My timing tests indicate it is actually faster.


My systems do not have realpath as suggested by rozcietrzewiacz.

You can accomplish this using the readlink command. The advantage of using this over parsing which or other solutions is that even if a part of the path or the filename executed was a symlink, you would be able to find the directory where the actual file was.

MYDIR="$(dirname "$(readlink -f "$0")")"

Your text file could then be read into a variable like this:

TEXTFILE="$(<$MYDIR/textfile)"

$0 in the script will be the full path to the script, and dirname will take a full path and give you just the directory, so you can do this to cat textfile:

$ cat "$(dirname -- "$0")/textfile"

Tags:

Bash

Path