#!/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"

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?

Edited 2 Years Ago by chriswelborn

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%/*}"