$0 doesn't have full directory path

I'm running AIX unix korn shell. If I echo $0, I only get the filename, it does not have the directory name also. So when I do: `dirname $0` it returns a . (meaning current directory). How get $0 to return the full path/filename? Do I need something in my .profile? Thank you.

$0 will equal however the program is called on the command line.

I believe you want the "whence" command, combined with the basename command.

Code:

$ cat efs1
#!/usr/dt/bin/dtksh

program=$(whence $(basename ${0}))

print $program

exit 0
$

No matter how it is called, you get the full path:

$ efs1
/home2/blahblah/efs1
$ ./efs1
/home2/blahblah/efs1
$ /home2/blahblah/efs1
/home2/blahblah/efs1
$

The whence didn't help either.
unix script:

#!/bin/ksh

echo zero: $0

dir1=`dirname $0`
echo dir1: $dir1

program=$(whence $(dirname ${0}))
echo $program

output:

zero: dirname_test1.sh
dir1: .
.
program=$(whence $0)
program_dir=$(cd $(dirname $program);pwd)

Jean-Pierre.

You don't want to do a whence on the dirname, but on the basename. Basename is the name of the program that is running, less the path of however it was called. Whence will return the path to the basename.

I found it - at the command line when I type in the full path of the shell script the $0 will be the full path with filename. Before at the command line I was in the directory and just typing the shell script name. Thanks

Exactly, that is why you want to strip out the path part of $0 by using basename first.

@gary_w if you strip out the path part of $0 you could report wrong file eg: ./ls would report /usr/bin/ls instead of /home/garyw/ls

On ksh it's probably best to use one of :

realpath $(whence $0)
readlink -f $(whence $0)

Or for bash

realpath $(type -p $0)
readlink -f $(type -p $0)
1 Like

Excellent point. I am not aware of the realpath or readlink commands, I will look them up tomorrow.

Thanks for adding this info!

Gary