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

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! :)


You can try this awk command:

 basedirectory=$(echo "$PATH" | awk -F "/" '{print $2}')

At this point basedirectory will be the string home Then you write:

rm -rf ./"$basedirectory"/