Bash - Get Name of Parent Directory

02 Mar 2015

For the path /foo/bar/, if the current directory is bar, and we want to get the name of the parent directory (i.e. foo)

path="$( cd "$( dirname $0 )" && cd -P "$( dirname "$SOURCE" )" && pwd )"
parentName=$(basename -- "$(dirname -- "$path")")
echo $parentName # will return parent directory's name

This resolves symbolic links (sidestepping the error where it returns “.” for the parent dir). Give it a try.