Getting the parent of a directory in Bash

前端 未结 12 1052
忘了有多久
忘了有多久 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 06:37

    Motivation for another answer

    I like very short, clear, guaranteed code. Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.

    Principle

    Not sure about what guarantees you have and want, so offering anyway.

    If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.

    Answer from simple to more complex cases of the original question.

    If path is guaranteed to end without any slash (in and out)

    P=/home/smith/Desktop/Test ; echo "${P%/*}"
    /home/smith/Desktop
    

    If path is guaranteed to end with exactly one slash (in and out)

    P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
    /home/smith/Desktop/
    

    If input path may end with zero or one slash (not more) and you want output path to end without slash

    for P in \
        /home/smith/Desktop/Test \
        /home/smith/Desktop/Test/
    do
        P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
    done
    
    /home/smith/Desktop
    /home/smith/Desktop
    

    If input path may have many extraneous slashes and you want output path to end without slash

    for P in \
        /home/smith/Desktop/Test \
        /home/smith/Desktop/Test/ \
        /home/smith///Desktop////Test// 
    do
        P_NODUPSLASH="${P//\/*(\/)/\/}"
        P_ENDNOSLASH="${P_NODUPSLASH%%/}"
        echo "${P_ENDNOSLASH%/*}";   
    done
    
    /home/smith/Desktop
    /home/smith/Desktop
    /home/smith/Desktop
    

提交回复
热议问题