Get current scripts path/location and name.

chriswelborn -1 Tallied Votes 472 Views Share

Grabs the location and name of the script file itself.

#!/bin/bash

# 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.
scriptreal="${BASH_SOURCE[0]}"
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]})"
APPSCRIPT="${APPPATH##*/}"
APPDIR="${APPPATH%/*}"
Be a part of the DaniWeb community

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