【发布时间】:2011-10-10 12:10:55
【问题描述】:
使用 bash,我如何编写 if 语句来检查存储在名为“$DIR”的脚本变量中的某个目录是否包含不是“.”的子目录还是“..”?
谢谢,- 戴夫
【问题讨论】:
使用 bash,我如何编写 if 语句来检查存储在名为“$DIR”的脚本变量中的某个目录是否包含不是“.”的子目录还是“..”?
谢谢,- 戴夫
【问题讨论】:
试试这个作为你测试的条件:
subdirs=$(ls -d $DIR/.*/ | grep -v "/./\|/../")
如果没有子目录,子目录将为空
【讨论】:
正如 cmets 所指出的,过去 9 年情况发生了变化!点目录不再作为 find 的一部分返回,而是在 find 命令中指定的目录。
所以,如果您想继续使用这种方法:
#!/bin/bash
subdircount=$(find /tmp/test -maxdepth 1 -type d | wc -l)
if [[ "$subdircount" -eq 1 ]]
then
echo "none of interest"
else
echo "something is in there"
fi
(最初接受 2011 年的答案)
#!/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
【讨论】:
find 命令时,如果不存在子文件夹,它会返回文件夹路径/d/temp。 ./ 和 ../ 未计算在内。
怎么样:
num_child=`ls -al $DIR | grep -c -v ^d`
如果 $num_child > 2,那么你有子目录。如果您不想隐藏目录,请将 ls -al 替换为 ls -l。
if [ $num_child -gt 2 ]
then
echo "$num_child child directories!"
fi
我不太确定你想在这里做什么,但你可以使用find:
find /path/to/root/directory -type d
如果你想编写脚本:
find $DIR/* -type d
应该可以解决问题。
【讨论】:
find /path/to/root/directory -mindepth 1 -type d
纯 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
【讨论】:
这是一个更简约的解决方案,它将在一行中执行测试..
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 directory。 2>&1 捕获 stderr 并将其通过管道传输到 stdout 中,然后将整个部分通过管道传输到 null (这消除了常规的 ls 输出也有文件时)。
【讨论】:
ls $DIR/*/ &>/dev/null && echo Subdirs || echo No-subdirs
ls $1/*/ >/dev/null 2>&1
在我的情况下,它不像 @AIG 所写的那样工作 - 对于空目录,我得到 subdircount=1(find 只返回 dir 本身)。
什么对我有用:
#!/usr/bin/bash
subdircount=`find /d/temp/ -maxdepth 1 -type d | wc -l`
if [ $subdircount -ge 2 ]
then
echo "not empty"
else
echo "empty"
fi
【讨论】:
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
【讨论】: