linux - 统计bash中可执行文件的数量

标签 linux bash shell ubuntu

我已经看到了很多关于这个主题的答案,但我不想使用 查找。我已经写了这个,但有些东西不起作用:

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/

相关文章:

linux - 如何在 ssh 命令中转义引号

linux - 默认情况下,当我们尝试从中创建 AMI 时,实例会重新启动吗?

macos - 在 MacOS 中仅删除一个用户的 ACL 条目?出奇地困难

bash:无法让简单的 'if' 工作

linux - 这行代码在 shell 中是如何工作的?

linux - ls 在目录中获取文件列表

c++ - 来自 2 个指针的组合缓冲区,无需复制

Linux读取空格和特殊字符

linux - Bash - 使用 socat 的代理服务器

linux - 如何在 bash 脚本中使用 awk 检查文件是否为空?