Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to design bash script in unix and this bash return full path because I want to use this file in other places.

share|improve this question
Full path of what? Self, as in the full path of the running script or some other object? A text string passed to your script as an argument? – Caleb Oct 4 '10 at 14:10
up vote 1 down vote accepted

Are you looking for the full path and filename of the running script?


_my_name=basename $0

if [ "echo $0 | cut -c1" = "/" ]; then

 _my_path=`dirname $0`


 _my_path=`pwd`/`echo $0 | sed -e s/$_my_name//`


echo " Filename: $_my_name"

echo "Absolute path: $_my_path"

echo "Full Path + Name: $0"

share|improve this answer
@Osama Ahmad: See BashFAQ/028. – Dennis Williamson Oct 4 '10 at 14:32

Give this a try if you have readlink on your system:

readlink -e filename
share|improve this answer
i try to execute it and this is a result ` readlink: not found` – Mohammad AL-Rawabdeh Oct 4 '10 at 13:57
readlink is not on every un*x (it's specific to gnu) – michael_n Apr 14 '13 at 3:20

Since this question is not trying to answer the harder question of converting a path with symbolic links into a physical path (w/o any links), but rather just get the directory and/or full path to the original script, there is a simpler solution (broken down in this example into components for legibility, plus you may want to use any of these pieces individually):

PROG_PATH=${BASH_SOURCE[0]}      # this script's name
PROG_NAME=${PROG_PATH##*/}       # basename of script (strip path)
PROG_DIR=$(cd "$(dirname "${PROG_PATH:-$PWD}")" 2>/dev/null 1>&2 && pwd)

echo "script directory is: $PROG_DIR"

Your test cases should involve calling this script with an absolute path, relative path, "sourcing" it, etc., and always ending up with the directory containing the script.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.