Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 402
user2966991 Avatar asked Jul 08 '14 12:07

user2966991


3 Answers

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

like image 164
user2966991 Avatar answered Sep 20 '22 19:09

user2966991


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"/
like image 41
condorwasabi Avatar answered Sep 20 '22 19:09

condorwasabi


If PATH always has an absolute form you can do tricks like

ROOT=${PATH#/} ROOT=/${ROOT%%/*}

Or

IFS=/ read -ra T <<< "$PATH"
ROOT=/${T[1]}

However I should also add to that that it's better to use other variables and not to use PATH as it would alter your search directories for binary files, unless you really intend to.

Also you can opt to convert your path to absolute form through readlink -f or readlink -m:

ABS=$(readlink -m "$PATH")

You can also refer to my function getabspath.

like image 27
konsolebox Avatar answered Sep 24 '22 19:09

konsolebox