Link to home
Start Free TrialLog in
Avatar of CAOgdin
CAOgdin

asked on

Finding a bash script's full path

I'm wondering if any experts in bash could offer me a better way to computer the full pathname to $0 in a script.

Specifically, I need to know the path the script is in, so it can do it's work in that (and only in that) directory.

Right now, I'm using the following four lines:
DIR="$PWD/`dirname $0`"      #Compute a full path name to this script
DIR=${DIR%.}            #Strip off trailing period
DIR=${DIR%\/}            #Strip off trailing slash
DIR=${DIR/\/\/\//\/}#Reduce any initial /// to /

The first line creates a full path, but it may have some strangeness (e.g., a trailing period if the bash script is launched directly from the directory, the odd trailing "/" in some cases, and the problem of "///home/xyz/abc", which $PWD can produce.

This four-line sequence works; I'm interesting in finding out of there any easier way to do this for my future bash scripts
Avatar of ozo
ozo
Flag of United States of America image

which $0
Avatar of CAOgdin
CAOgdin

ASKER

Nice one.  I wonder how it missed that command.

Still not quite there, though.  I need it without the name of the script...just the path to the script itself.

It returns /home/xyz/abc/test for a script named "test."  I need just /home/xyz/abc
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CAOgdin

ASKER

Slick!  I'm impressed (and it urges me on to learn more about bash).

Thanks.