Bash Path – Refer to a File Under Same Directory of a Script in $PATH

bashpath

I have a bash script file, which is put under some directory added to $PATH so that I can call the script from any directory.

There is another text file under the same directory as the script. I wonder how to refer to the text file in the script?

For example, if the script is just to output the content of the text file, cat textfile won't work, since when calling the script from a different directory, the text file is not found.

Best Answer

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.

Related Question