mike23
mike23

Reputation: 1312

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.

Upvotes: 4

Views: 15563

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360075

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

Upvotes: 12

glenn jackman
glenn jackman

Reputation: 246807

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

Upvotes: 6

Related Questions