如何检查目录是否包含子目录?

时间:2011-07-21 18:57:18

标签: bash unix scripting

使用bash,如何编写if语句,检查存储在名为“$ DIR”的脚本变量中的某个目录是否包含不是“。”的子目录。还是“......”?

谢谢, - 戴夫

8 个答案:

答案 0 :(得分:11)

这是一种方式:

#!/usr/bin/bash
subdircount=`find /d/temp/ -maxdepth 1 -type d | wc -l`

if [ $subdircount -eq 2 ]
then
    echo "none of interest"
else
    echo "something is in there"
fi

答案 1 :(得分:5)

这是一个更简约的解决方案,可以在一行中执行测试。

ls $DIR/*/ >/dev/null 2>&1 ; 

if [ $? == 0 ]; 
then 
  echo Subdirs
else 
  echo No-subdirs
fi

/放在*通配符之后,您只选择目录,因此如果没有目录,则ls将返回错误状态 2 并打印消息ls: cannot access <dir>/*/: No such file or directory2>&1捕获 stderr 并将其传输到 stdout ,然后整个地块被传送到 null (摆脱了常规ls输出,当有文件时。)

答案 2 :(得分:4)

我不确定你在这里做什么,但你可以使用find

find /path/to/root/directory -type d

如果你想编写脚本:

find $DIR/* -type d

应该这样做。

答案 3 :(得分:2)

尝试将此作为您测试的条件:

subdirs=$(ls  -d $DIR/.*/ | grep -v "/./\|/../")
如果没有子目录,

子目录将为空

答案 4 :(得分:2)

纯粹的bash解决方案,无需任何其他程序执行。这不是最紧凑的解决方案,但如果在循环中运行,它可能更有效,因为不需要创建进程。如果'$dir'中有很多文件,文件名扩展可能会破坏。

shopt -s dotglob   # To include directories beginning by '.' in file expansion.
nbdir=0
for f in $dir/*
do
  if [ -d $f ]
  then
    nbdir=$((nbdir+1))
  fi
done

if [ nbdir -gt 0 ]
then
   echo "Subdirs"
else
   echo "No-Subdirs"
fi

答案 5 :(得分:0)

怎么样:

num_child=`ls -al $DIR | grep -c -v ^d`

如果$ num_child&gt; 2,然后你有子目录。如果您不想隐藏目录,请将ls -al替换为ls -l。

if [ $num_child -gt 2 ]
then
    echo "$num_child child directories!"
fi

答案 6 :(得分:0)

在我的情况下它不起作用@AIG写道 - 对于空目录我得到了subdircount = 1(找到只返回dir本身)。

什么对我有用:

Map

答案 7 :(得分:0)

这是您将在此问题上看到的最佳答案。

function hasDirs ()
{
    declare $targetDir="$1"    # Where targetDir ends in a forward slash /
    ls -ld ${targetDir}*/
}

如果您已经在目标目录中:

if hasDirs ./
then

fi

如果您想了解另一个目录:

if hasDirs /var/local/   # Notice the ending slash
then

fi