How to get the root directory of a 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 the first folder "$ PATH": / home /

  cd /tmp/backup rm -rf ./home/ cd - > /dev/null 

How can I always find the first folder, as in the example above? "dirname $ PATH" simply returns "/ home / user / example / foo /".

Thanks in advance!:)

+6
source share
4 answers

I found a solution:

  #/usr/bin/env bash DIRECTORY="/home/user/example/foo/bar" BASE_DIRECTORY=$(echo "$DIRECTORY" | cut -d "/" -f2) echo "#$BASE_DIRECTORY#"; 

This always returns the first directory. In this example, it will return the following:

  #home# 

Thanks to @condorwasabi for his idea with awk! :)

+12
source

You can try this awk command:

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

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

 rm -rf ./"$basedirectory"/ 
+2
source

If PATH always absolute, you can do tricks, for example

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

or

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

However, I must add to this that it is better to use other variables and not use PATH , as this will change your search directories for binaries if you really do not intend.

You can also convert your path to absolute form via readlink -f or readlink -m :

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

You can also refer to my getabspath function.

+1
source

To get the first directory:

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

PS: Never use the PATH variable in a script, since it will override the default PATH, and you script will not be able to execute many system utilities

EDIT: Maybe this will work for you:

 IFS=/ && set -- $path; echo "$2" home 
0
source

Source: https://habr.com/ru/post/971917/


All Articles