How-To get root directory of given path in bash?

user2966991 picture user2966991 · Jul 8, 2014 · Viewed 51.1k times · Source

My script:

    #!/usr/bin/env bash
    PATH=/home/user/example/foo/bar
    mkdir -p /tmp/backup$PATH

And now I want to get first folder of "$PATH": /home/

    cd /tmp/backup
    rm -rf ./home/
    cd - > /dev/null

How can I always detect the first folder like the example above? "dirname $PATH" just returns "/home/user/example/foo/".

Thanks in advance! :)

Answer

user2966991 picture user2966991 · Jul 9, 2014

I've found a solution:

    #/usr/bin/env bash
    DIRECTORY="/home/user/example/foo/bar"
    BASE_DIRECTORY=$(echo "$DIRECTORY" | cut -d "/" -f2)
    echo "#$BASE_DIRECTORY#";

This returns always the first directory. In this example it would return following:

    #home#

Thanks to @condorwasabi for his idea with awk! :)