Getting the parent of a directory in Bash
Clearly the parent directory is given by simply appending the dot-dot filename:
/home/smith/Desktop/Test/.. # unresolved path
But you must want the resolved path (an absolute path without any dot-dot path components):
/home/smith/Desktop # resolved path
The problem with the top answers that use dirname
, is that they don't work when you enter a path with dot-dots:
$ dir=~/Library/../Desktop/../..
$ parentdir="$(dirname "$dir")"
$ echo $parentdir
/Users/username/Library/../Desktop/.. # not fully resolved
This is more powerful:
dir=/home/smith/Desktop/Test
parentdir=$(builtin cd $dir; pwd)
You can feed it /home/smith/Desktop/Test/..
, but also more complex paths like:
$ dir=~/Library/../Desktop/../..
$ parentdir=$(builtin cd $dir; pwd)
$ echo $parentdir
/Users # the fully resolved path!
NOTE: use of builtin
ensures no user defined function variant of cd
is called, but rather the default utility form which has no output.
dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"
Works if there is a trailing slash, too.
Just use echo $(cd ../ && pwd)
while working in the directory whose parent dir you want to find out. This chain also has the added benefit of not having trailing slashes.