Getting the parent of a directory in Bash

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

    if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd). This would give 3 parents directories up

    0 讨论(0)
  • 2020-12-04 06:25

    ...but what is "seen here" is broken. Here's the fix:

    > pwd
    /home/me
    > x='Om Namah Shivaya'
    > mkdir "$x" && cd "$x"
    /home/me/Om Namah Shivaya
    > parentdir="$(dirname "$(pwd)")"
    > echo $parentdir
    /home/me
    
    0 讨论(0)
  • 2020-12-04 06:25

    This would go up to the parent folder

    cd ../
    
    0 讨论(0)
  • 2020-12-04 06:26

    use this : export MYVAR="$(dirname "$(dirname "$(dirname "$(dirname $PWD)")")")" if you want 4th parent directory

    export MYVAR="$(dirname "$(dirname "$(dirname $PWD)")")" if you want 3rd parent directory

    export MYVAR="$(dirname "$(dirname $PWD)")" if you want 2nd parent directory

    0 讨论(0)
  • 2020-12-04 06:34
    dir=/home/smith/Desktop/Test
    parentdir="$(dirname "$dir")"
    

    Works if there is a trailing slash, too.

    0 讨论(0)
  • 2020-12-04 06:37

    Just use echo $(cd ../ && pwd) while working in the directory whose parent dir you want to find out. This chain also has the added benefit of not having trailing slashes.

    0 讨论(0)
提交回复
热议问题