tags:

views:

1857

answers:

7

Is it possible to find out the full path to the script that is currently executing in Korn shell?

i.e. if my script is in /opt/scripts/myscript.ksh, can I programmatically inside that script discover '/opt/scripts/myscript.ksh'?

Thanks,

+3  A: 

How the script was called is stored in the variable $0. You can use readlink to get the absolute file name:

readlink -f "$0"
soulmerge
thanks for the $0 tip, what's readlink? doesn't seem to be on my system
Brabster
readlink is a simple app in the gnu coreutils package
soulmerge
Hmmm need something totally within ksh, no dependencies. Thanks though
Brabster
I'm afraid that won't be possible - unless ksh has a possibility I am not aware of for interacting with the file system. What's your OS?
soulmerge
+5  A: 

You could use:

## __SCRIPTNAME - name of the script without the path
##
typeset -r __SCRIPTNAME="${0##*/}"

## __SCRIPTDIR - path of the script (as entered by the user!)
##
__SCRIPTDIR="${0%/*}"

## __REAL_SCRIPTDIR - path of the script (real path, maybe a link)
##
__REAL_SCRIPTDIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
Marnix
thanks @Marnix, works a treat
Brabster
A: 

This works also, although it won't give the "true" path if it's a link. It's simpler, but less exact.

SCRIPT_PATH="$(whence ${0})"
mtruesdell
A: 

Try which command.

which scriptname

will give you the full qualified name of the script along with its absolute path

Sachin Chourasiya
A: 

"readlink -f" would be the best if it was portable, because it resolves every links found for both directories and files.

On mac os x there is no "readlink -f" (except maybe via macports), so you can only use "readlink" to get the destination of a specific symbolic link file.

The $(cd -P ... pwd -P) technique is nice but only works to resolve links for directories leading to the script, it doesn't work if the script itself is a symlink

Also, one case that wasn't mentionnend : when you launch a script by passing it as an argument to a shell (/bin/sh /path/to/myscript.sh), "$0" is not usable in this case

I took a look to mysql "binaries", many of them are actually shell scripts ; and now i understand why they ask for a --basedir option or need to be launched from a specific working directory ; this is because there is no good solution to locate the targeted script

Gruik
A: 

use this :

dir = $(dirname $0)

kailash
A: 

This is what I did:

if [[ $0 != "/"* ]]; then
  DIR=`pwd`/`dirname $0`
else
  DIR=`dirname $0`
fi
John Nilsson