How to find Linux bash script path (Self Path)

Blog
Linux
Sys Administration

Writing smart programs using bash script is not easy, there are many issues along the way and one of them is what i'm going to describe here.

Sometimes it's require for bash scripts to know their location, for example when they are part of a package and there are other require files (on the same location) for them to run properly, and it's also not possible to change the path to where they're located simply because they also need the current directory.

After reading dozens of articles , testing results and combining them i came up with a simple function which can get the job done cleanly.

# Begin - Set script working dir and include dependencies
getScriptPath () {
	if [ -d ${0%/*} ]
	then
		abspath=$(cd ${0%/*} && echo $PWD/${0##*/})
		# to get the path only - not the script name - add
		pathOnly=`dirname "$abspath"`
	else
		progdir=`dirname $0`
		cd $progdir
		pathOnly=$PWD
	fi

	echo $pathOnly;
	return
}
currentPath=$(getScriptPath)
cd $currentPath
# End - Set script working dir and include dependencies

The function tested under CentOS and Ubuntu , i also like to kown if it works on other distributions as well. So feedbacks are welcomed

Your rating: None Average: 3 (1 vote)