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/Testparentdir=$(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.