Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - How to get the name a folder inside the current folder?

Let's say my script is running inside a folder, and in this folder is anther folder with a name that can change each time I run the script. How can I find the name of that folder ?

Edit :

As an example, let's say my script is running in the folder /testfolder, which is known and does not change.

In /testfolder there is another folder : /testfolder/randomfolder, which is unknown and can change.

How do I find the name of /randomfolder ?

I hope it's clearer, sorry for the confusion.

like image 845
mike23 Avatar asked Dec 01 '22 22:12

mike23


2 Answers

dirs=(/testfolder/*/)

dirs will be an array containing the names of each directory that is a direct subdirectory of /testfolder.

If there's only one, you can access it like this:

echo "$dirs"

or

echo "${dirs[0]}"

If there is more than one and you want to iterate over them:

for dir in "${dirs[@]}"
do
    echo "$dir"
done
like image 200
Dennis Williamson Avatar answered Dec 20 '22 09:12

Dennis Williamson


Assuming there is exactly one subdirectory:

dir=$(find . -mindepth 1 -maxdepth 1 -type d)

If you don't have GNU find, then

for f in *; do [[ -d "$f" ]] && { dir=$f; break; }; done
like image 33
glenn jackman Avatar answered Dec 20 '22 07:12

glenn jackman