Getting the parent of a directory in Bash

前端 未结 12 1061
忘了有多久
忘了有多久 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:49

    ugly but efficient

    function Parentdir()
    

    {

    local lookFor_ parent_ switch_ i_
    
    lookFor_="$1"
    
    #if it is not a file, we need the grand parent
    [ -f "$lookFor_" ] || switch_="/.."
    
    #length of search string
    i_="${#lookFor_}"
    
    #remove string one by one until it make sens for the system
    while [ "$i_" -ge 0 ] && [ ! -d "${lookFor_:0:$i_}" ];
    do
        let i_--
    done
    
    #get real path
    parent_="$(realpath "${lookFor_:0:$i_}$switch_")" 
    
    #done
    echo "
    lookFor_: $1
    {lookFor_:0:$i_}: ${lookFor_:0:$i_}
    realpath {lookFor_:0:$i_}: $(realpath ${lookFor_:0:$i_})
    parent_: $parent_ 
    "
    

    }

        lookFor_: /home/Om Namah Shivaya
    {lookFor_:0:6}: /home/
    realpath {lookFor_:0:6}: /home
    parent_: /home 
    
    
    lookFor_: /var/log
    {lookFor_:0:8}: /var/log
    realpath {lookFor_:0:8}: /UNIONFS/var/log
    parent_: /UNIONFS/var 
    
    
    lookFor_: /var/log/
    {lookFor_:0:9}: /var/log/
    realpath {lookFor_:0:9}: /UNIONFS/var/log
    parent_: /UNIONFS/var 
    
    
    lookFor_: /tmp//res.log/..
    {lookFor_:0:6}: /tmp//
    realpath {lookFor_:0:6}: /tmp
    parent_: / 
    
    
    lookFor_: /media/sdc8/../sdc8/Debian_Master//a
    {lookFor_:0:35}: /media/sdc8/../sdc8/Debian_Master//
    realpath {lookFor_:0:35}: /media/sdc8/Debian_Master
    parent_: /media/sdc8 
    
    
    lookFor_: /media/sdc8//Debian_Master/../Debian_Master/a
    {lookFor_:0:44}: /media/sdc8//Debian_Master/../Debian_Master/
    realpath {lookFor_:0:44}: /media/sdc8/Debian_Master
    parent_: /media/sdc8 
    
    
    lookFor_: /media/sdc8/Debian_Master/../Debian_Master/For_Debian
    {lookFor_:0:53}: /media/sdc8/Debian_Master/../Debian_Master/For_Debian
    realpath {lookFor_:0:53}: /media/sdc8/Debian_Master/For_Debian
    parent_: /media/sdc8/Debian_Master 
    
    
    lookFor_: /tmp/../res.log
    {lookFor_:0:8}: /tmp/../
    realpath {lookFor_:0:8}: /
    parent_: /
    

提交回复
热议问题