Getting the parent of a directory in Bash
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/
Solution 1:
dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"
Works if there is a trailing slash, too.
Solution 2:
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.