Get current scripts path/location and name.


Grabs the location and name of the script file itself.

About the Author

All-around coder/developer for desktop/web/etc. Windows & Linux admin. Super-User.


# Example of how to get script file/path info.
# -chriswelborn

# This will work even if the script is symlinked
# and called from another directory.
# It does not show the CWD (current working dir), 
# but the location of this script itself.
scriptpath="$(realpath $scriptreal)"
scriptdir="$(dirname $scriptpath)"
scriptname="$(basename $scriptpath)"

echo "Real:"
echo "    path: $scriptpath"
echo "     dir: $scriptdir"
echo "    name: $scriptname"
cfajohnson 7 Shell scripter and author

If you think you need to know the location of the script, you need to rethink what you are doing.

Also, there's no need to use external commands basename and dirname in bash (or any other POSIX shell; use parameter expansion).

This question comes up a lot. There are almost 13 million google-results for 'get bash scripts actual directory', for what that's worth. Most people use it to ensure that a file is present, relative to the location of the script, no matter where or how the script is executed.

Maybe you could show a parameter expansion example?

Here is the parameter expansion version, which seems to be better than calling 2 unnecessary commands:

APPPATH="$(realpath ${BASH_SOURCE[0]})"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.