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.
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.
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
BASH_SOURCEAn array variable whose members are the source filenames where the corresponding shell function names in the
FUNCNAMEarray variable are defined. The shell function${FUNCNAME[$i]}is defined in the file${BASH_SOURCE[$i]}and called from${BASH_SOURCE[$i+1]}
readlink in case this file is being sourced with relative path.$_ 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)
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.
realpath.Assuming you have the realpath command installed, you can replace this code by the simple:
fullpath=`realpath "$_"`