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

前端 未结 6 1676
你的背包
你的背包 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
    

提交回复
热议问题