【问题标题】:Counting number of executable files in every variable inside PATH计算 PATH 内每个变量中的可执行文件数
【发布时间】:2018-10-02 15:05:06
【问题描述】:

我想编写一个脚本来计算变量 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

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

【问题讨论】:

  • 这可以是一行 php,但像往常一样,我会被菜鸟否决。对于 bash 脚本,php 在各个方面都比 bash 本身要好。

标签: linux bash shell


【解决方案1】:

您是否考虑过使用 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

【讨论】:

  • find -print 的输出连接到wc 并不比使用ls 的输出好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多