Bash script to get its full path (use 'source' to invoke it)

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.


Use realpath .

$ realpath ~/dev/setup.sh

In a script:

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

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]}


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 "$_"`
链接地址: http://www.djcxy.com/p/56814.html

上一篇: 将输入和输出文件所需的PATH传递给bash中的二进制文件

下一篇: Bash脚本获取完整路径(使用'source'来调用它)