bashpathdirectorydirname

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


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


Solution

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