Getting the parent of a directory in Bash

YTKColumba picture YTKColumba · Dec 8, 2011 · Viewed 203k times · Source

If I have a file path such as...

/home/smith/Desktop/Test
/home/smith/Desktop/Test/

How do I change the string so it will be the parent directory?

e.g.

/home/smith/Desktop
/home/smith/Desktop/

Answer

Michael Hoffman picture Michael Hoffman · Dec 8, 2011
dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.