计算PATH内每个变量中的可执行文件数

时间:2018-04-22 13:19:02

标签: linux bash shell

我想编写一个脚本来计算变量PATH中每个文件夹中的可执行文件数。我的代码:

#!/bin/bash

IFS=":"
for directory in $PATH; do
        files=0
        ls -l $directory | while read rights x name group siz m d h name; do
                if [ `echo $rights | cut -c1` = "-" ]; then
                        files=$((${files}+1))
                fi
        done
        echo "Directory ${directory} contains ${files} executable files"
done

我想在while循环结束之后和next循环开始之前处理echo,但它总是打印出文件数= 0. if条件内的计数有效。

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用find命令?见link。在基于GNU的find版本中,类似下面的内容应该替换你的ls调用和while循环。

find $directory -type f -executable -print | wc -l

如果您担心遍历子目录,可以使用maxdepth标志,即

find $directory -maxdepth 1 -type f -executable -print | wc -l

对于BSD版本,请再次参阅link