bash 检查目录是否包含特定的子目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28335230/
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 12:19:46  来源:igfitidea点击:

Check if a directory contains a particular subdirectory

bashshellunix

提问by Rumen Hristov

I am trying to write a shell script, which checks if a given directory contains a particularly named subdirectory. I am passing the Parent directory as a first argument and only the name for the child directory. I want the script to go through the contents of the Parent and see if it contains a file of type directory, which is named with the name I am passing in for Child.

我正在尝试编写一个 shell 脚本,它检查给定的目录是否包含一个特别命名的子目录。我将父目录作为第一个参数传递,并且只传递子目录的名称。我希望脚本遍历 Parent 的内容,看看它是否包含一个目录类型的文件,该文件以我为 Child 传递的名称命名。

This is my code. In it I am trying to pipe the output of lson the Parent to the egrepcommand. I am trying to write a regular expression that checks to see if the output of lshas a name that matches (not identically. just somewhere in its name) my child name.

这是我的代码。在其中,我试图ls将 Parent 上的输出通过管道传输到egrep命令。我正在尝试编写一个正则表达式来检查输出的ls名称是否与我的孩子的名字匹配(不完全相同。只是在它的名字中的某个地方)。

PARENT=
CHILD=

DIRNUM=$(ls -l $PARENT | egrep -c '< $CHILD >')
echo $DIRNUM

回答by Etan Reisner

Don't do this. Don't parse ls.

不要这样做。不要解析ls

Just check for the file/directory directly with the [/testbuilt-in/command.

只需使用[/testbuilt-in/command直接检查文件/目录。

path=$parent/$child
if [ -d "$path" ]; then
    echo "$path exists."
else
    echo "$path does not exist."
fi

You'll note that I switched case on the variable names. ALL_UPPER variables are "reserved" for the shell's use you shouldn't use any.

您会注意到我在变量名称上切换了大小写。ALL_UPPER 变量是“保留”的,供 shell 使用,您不应使用任何变量。

回答by Claudio Corsi

Use the find command like the following:

使用 find 命令,如下所示:

# find $parent -name \*${child}\* -and -type d

The type option is to insure that the found name is a directory.

type 选项是为了确保找到的名称是一个目录。

This command will find all sub-directories located within $parent that contain $child in its name

此命令将查找位于 $parent 中名称中包含 $child 的所有子目录