Bash - 如何获取当前文件夹中文件夹的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10605304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:16:38  来源:igfitidea点击:

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

bashshelldirectory

提问by mike23

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.

例如,假设我的脚本正在文件夹 中运行,该文件夹/testfolder是已知且不会更改的。

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

/testfolder还有另一个文件夹 : /testfolder/randomfolder,这是未知的并且可以更改。

How do I find the name of /randomfolder?

我如何找到 的名字/randomfolder

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

我希望它更清楚,对混淆感到抱歉。

回答by Paused until further notice.

dirs=(/testfolder/*/)

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

dirs将是一个包含每个目录名称的数组,该目录是/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

回答by glenn Hymanman

Assuming there is exactly one subdirectory:

假设只有一个子目录:

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

If you don't have GNU find, then

如果你没有找到 GNU,那么

for f in *; do [[ -d "$f" ]] && { dir=$f; break; }; done