Getting the parent of a directory in Bash

前端 未结 12 1049
忘了有多久
忘了有多久 2020-12-04 06:11

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 dir

12条回答
  •  鱼传尺愫
    2020-12-04 06:39

    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=`(/usr/bin/cd -- "$dir" && pwd)`
    

    You can feed it /home/smith/Desktop/Test/.., but also more complex paths like:

    $ dir=~/Library/../Desktop/../..
    $ parentdir=`(/usr/bin/cd -- "$dir" && pwd)`
    $ echo $parentdir
    /Users                                  # the fully resolved path!
     
    

提交回复
热议问题