Perl’s FindBin is handy when a script needs to know its home. What is the bash equivalent of Perl FindBin? Here are some options.

#!/bin/bash
Bin="$( readlink -f -- "$( dirname -- "$0" )" )"
echo $Bin

To avoid the dirname fork, you can replace it with a variable manipulation.

Bin="$( readlink -f -- "${0%/*}" )"

The ‘%’ operator deletes the shortest possible match from the right, so will remove the file name and terminal ‘/’ from the $0 (the command executing).

Finally, there’s the “go there and see for yourself” approach.

Bin="$(cd -- "$(dirname "$0")" && pwd)"

In all cases I’m trying to be careful to quote the variables and expressions to allow for spaces in path names. Also, I’m adding -- after commands as a signal to stop scanning for options. Otherwise, if a pathname beginning with a - would be interpreted as an option.

Advertisements