how to find Script file location inside script

I have to find out the file system location of the script file inside script. for example a script "abc.sh" placed anywhere in the file system when executed shold tell by itself the location of it.

example

#pwd
/
#./abc
this is /
#cd /root
#./abc
this is /root
#cd /
#/root/abc
this is /root

This should work.

[/tmp]$ cat pwd.ksh 
#! /bin/ksh

self="${0#./}"
base="${self%/*}"
current=$(pwd)

if [ "$base" = "$self" ] ; then
echo "$current"
else
echo "$current/$base"
fi ;

no it doesnt work

What doesnt work ?

Care to explain/show what is the output that you are getting ?

self="${0#./}"

The 0 you see is the digit 0 instead of the alphabet O

I see what you mean.

What you actually need is the contents of /proc/pid/exe. But in your case since you need the actual path of script that is run, /proc/pid/exe it wouldnt help because, the shell i.e. /bin/sh or /bin/ksh or /bin/bash et al., picks up your script and runs it. So a /proc/pid/exe inside a script would give you /bin/sh or /bin/ksh likewise.

What you can do is analyze $0 and see if it is a path starting from / and gets its basename. Else use it along with pwd of the current directory.

you are using $0 which is what is used to execute that script, if i used

../../../abc.sh such things are appearing the result. i want direct path

[/tmp]$ cat pwd.ksh 
#! /bin/ksh

self="${0#./}"
base="${self%/*}"
current=$(pwd)

if [ "$base" = "$self" ] ; then
{ cd "$current" ; echo $(pwd) ;}
else
{cd $current/$base ; echo $(pwd) ; }
fi ;

hi asami,
you can use driname command

path= `dirname $0`
echo $path

This will give you only the path of your script which is what you were looking for.

Asamy

have you tried with the command substition?

In your script try do insert this row

echo "We are in `pwd`"

I hope it is what you need.
^Nosfe^

hey vino thnx man, u guided my thirsty soul. the following works for me

#!/bin/bash

base=${0%/*}
current=`pwd`

cd $base
echo "The Path is `pwd`"
cd $current
using dirname
cur=`pwd`
path=`dirname $0`
cd $path
echo "`pwd`"
cd $cur