Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

3 Answers 3

up vote 1 down vote accepted

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

#!/bin/bash

_my_name=basename $0

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

 _my_path=`dirname $0`

else

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

fi

echo " Filename: $_my_name"

echo "Absolute path: $_my_path"

echo "Full Path + Name: $0"

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

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
add comment

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):

#!/bin/bash
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
add comment

Your Answer

 
discard

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.