Quote Originally Posted by ofnuts View Post
$PWD gives you the current directory, which isn't the directory where the shell script file is (can be invoked with an explicit path, or be somewhere in the PATH). The directory where the script comes from is obtained by:
Code:
mydir=$(dirname $0)
Actually OP was so badly worded I didn't know what he wanted. It occurred to me that was what he wanted but I dismissed it.
My preference would be:
PHP Code:
myname=${0##*/}
mydir=${0%/\*\} 
Quote Originally Posted by ofnuts View Post
In other words:
Code:
#! /bin/bash

me=$0
mydir=$(dirname $0)

echo "Me: $me"
echo "My dir: $mydir"
The problem is when you invoke the code as
PHP Code:
sh myprog 
you end up with mydir being null. You then have to add something like
PHP Code:
mydir=${mydir:-$PWD
And don't forget that if you invoke it with a relative path and then want to move to a different directory in the script ...

PHP Code:
#!/bin/bash
myname=${0##*/}
mydir=${0%/\*\}
mydir=${mydir:-$PWD}
mydir=$(cd $mydirpwd -p)

printf "mydir is %s\n" $mydir 
Basically what should happen is that mydir is set to something which is not null and then a subshell is invoked to go to the location of mydir and pass back the absolute path. But I haven't tested this so I may have it wrong.

Andrew