tags:

views:

226

answers:

3

Is there a less brute-force way to do this?

#!/bin/ksh
THIS_SCRIPT=$(/usr/bin/readlink -f $(echo $0 | /bin/sed "s,^[^/],$PWD/&,"))
echo $THIS_SCRIPT

I'm stuck using ksh but would prefer a solution that works in bash too (which I think this does).

+2  A: 

Why didn't I think to try this before I asked the question?

THIS_SCRIPT=$(/usr/bin/readlink -nf "$0")

Works great.

Dan
+3  A: 

Entry #28 in the bash FAQ.

Ignacio Vazquez-Abrams
Wow... I really didn't want to go down the rabbit hole that far, but that's a great answer. I'm going to stick with my `readlink` solution because it's good enough for what I'm doing, but I'll accept this answer.
Dan
+2  A: 

I've always done:

SCRIPT_PATH=$(cd `dirname ${0}`; pwd)

I've never used readlink before: is it Gnu only? (i.e. will it work on HP-UX, AIX, and Solaris out of the box? dirname and pwd will....)

(edited to add `` which I forgot in original post. d'oh!) (edit 2 to put on two lines which I've apparently always done when I look at previous scripts I'd written, but hadn't remembered properly. First call gets path, second call eliminates relative path) (edit 3 fixed typo that prevented single line answer from working, back to single line!)

Dana Lacoste