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

前端 未结 6 1616
你的背包
你的背包 2021-01-04 01:02

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

相关标签:
6条回答
  • 2021-01-04 01:13

    To get the first firectory:

    path=/home/user/example/foo/bar
    mkdir -p "/tmp/backup$path"
    cd /tmp/backup
    arr=( */ )
    echo "${arr[0]}"
    

    PS: Never use PATH variable in your script as it will overrider default PATH and you script won't be able to execute many system utilities

    EDIT: Probably this should work for you:

    IFS=/ && set -- $path; echo "$2"
    home
    
    0 讨论(0)
  • 2021-01-04 01:19

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

    0 讨论(0)
  • 2021-01-04 01:20

    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"/
    
    0 讨论(0)
  • 2021-01-04 01:28

    You can use dirname...

    #/usr/bin/env bash
    DIRECTORY="/home/user/example/foo/bar"
    BASE_DIRECTORY=$(dirname "${DIRECTORY}")
    echo "#$BASE_DIRECTORY#";
    

    Outputs the following...

    /home/user/example/foo
    
    0 讨论(0)
  • 2021-01-04 01:31

    Pure bash:

    DIR="/home/user/example/foo/bar"
    [[ "$DIR" =~ ^[/][^/]+ ]] && printf "$BASH_REMATCH"
    

    Easy to tweak the regex.

    0 讨论(0)
  • 2021-01-04 01:32

    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.

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