How to find Linux bash script path (Self Path)
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 dependenciesThe function tested under CentOS and Ubuntu , i also like to kown if it works on other distributions as well. So feedbacks are welcomed
- Path:
- Tags:


Recent comments
1 week 2 days ago
1 week 2 days ago
1 week 3 days ago
1 week 3 days ago
1 week 5 days ago
1 week 5 days ago
1 year 6 weeks ago
1 year 6 weeks ago
2 weeks 5 days ago
2 weeks 5 days ago