2

In a bash script, is there any method to get the full path of itself?

$ source ~/dev/setup.sh

I have tried $_, $-, $0..., but all are irrelevant.

Thanks in advance.

1

3 Answers 3

2

You can use BASH_SOURCE variable and then use readlink to get full path:

echo $BASH_SOURCE

# to get full path
fullpath=$(readlink --canonicalize --no-newline $BASH_SOURCE)
echo "$fullpath"

This will print the invoke path of the file being sourced, so in your case:

~/dev/setup.sh
~/dev/setup.sh

Reference

BASH_SOURCE

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Sign up to request clarification or add additional context in comments.

8 Comments

This doesn't provide the full path. It provides whatever relative path you run the script from.
That's what I mentioned in my answer that This will print the invoke path of the file being sourced
Yes, that's the answer. Thank you very much.
I've also added a suggestion of calling readlink in case this file is being sourced with relative path.
You may be aware that 5 min limit doesn't apply if a single comment appears and then it shows up in edit history
|
2

The $_ variable for location of a sourced script.

If you're sourcing the script, you can access the script name with $_ (since $0 will be the bash interpreter)

Pure bash solution.

relname="$_";

# if script is in current directory, add ./
if [[ ! "$relname" =~ "/" ]]; then 
   relname="./$relname"; fi

relpath=`dirname $relname`;
name="${relname##*/}"

# convert to absolute path by cd-ing and using pwd.
cd "$relpath" >/dev/null;
path=`pwd`;
cd - >/dev/null;

# construct full path from absolute path and filename
fullpath="$path/$name";

Note that this script has the side effect of replacing the $OLDPWD (used by cd -) by the script directory. If you need to avoid this, just save $OLDPWD before the cd - and restore it at the end.

Using realpath.

Assuming you have the realpath command installed, you can replace this code by the simple:

fullpath=`realpath "$_"`

Comments

-1

Use realpath.

$ realpath ~/dev/setup.sh

In a script:

rp=$(realpath "$0")
echo $rp

1 Comment

Note that one might want to give realpath some options, depending on how one would want it to deal with symlinks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.