我已经看到了很多关于这个主题的答案,但我不想使用
查找
。我已经写了这个,但有些东西不起作用:
function CountEx()
{
count=0
for file in `ls $1`
do
echo "file is $file"
if [ -x $file ]
then
count=`expr $count + 1`
fi
done
echo "The number of executable files in this dir is: $count"
}
while getopts x:d:c:h opt
do
case $opt in
x)CountEx $OPTARG;;
d)CountDir $OPTARG;;
c)Comp $OPTARG;;
h)help;;
*)echo "Please Use The -h Option to see help"
break;;
esac
done
我正在使用如下脚本:
yaser.sh -x './..../...../.....'
shell 运行它,然后输出:
该目录中可执行文件的数量为:0
当该目录中有很多可执行文件时。
最佳答案
如果您的目标是计算目录数量,那么有很多选择。
你说你不想要的find
方式:
CountDir() {
if [[ ! -d "$1" ]]; then
echo "ERROR: $1 is not a directory." >&2
return 1
fi
printf "Total: %d\n" $(find "$1" -depth 1 -type d | wc -l)
}
for
方式,类似于您的示例:
CountDir() {
if [[ ! -d "$1" ]]; then
echo "ERROR: $1 is not a directory." >&2
return 1
fi
count=0
for dir in "$1"/*; do
if [[ -d "$dir" ]]; then
((count++))
fi
done
echo "Total: $count"
}
set
方式,完全跳过循环。
CountDir() {
if [[ ! -d "$1" ]]; then
echo "ERROR: $1 is not a directory." >&2
return 1
fi
set -- "$1"/*/
echo "Total: $#"
}
关于linux - 统计bash中可执行文件的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832477/