【问题标题】:Count the number of executable files in bash统计bash中可执行文件的数量
【发布时间】:2013-02-12 12:23:12
【问题描述】:

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

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 运行它,然后输出: The number of executable files in this dir is: 0 当这个目录下有很多可执行文件时。

【问题讨论】:

  • 什么是“不工作”?很高兴您提供了代码,但您还应该包括您的预期和实际输出。如果您希望人们能够重现您的结果,那么更详细地描述输入会有所帮助。哦,你是 parsing LS。不要那样做。
  • 该脚本草率到足以破坏带有空格的目录,带有特殊字符的文件名以及谁知道还有什么,但它绝对可以在经过消毒的环境中工作(文件和目录名称没有什么特别的)。描述某事如何不适合你。
  • 根据以下答案的多样性,您是在寻找 executables 的数量(正如您在标题中所说),还是 子目录的数量 i>,正如您在代码中所暗示的那样?
  • 对不起,我把 CountDir 函数代替了 CountEx 但这是同样的问题,因为我想使用 ls 并传递给它 $1 然后计数可执行文件或目录的数量
  • 对不起,我刚刚更正了功能,

标签: linux bash shell ubuntu


【解决方案1】:

如果您的目标是计算目录,那么有很多选择。

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: $#"
}

【讨论】:

  • 对于find 缺少-type d,在for 方式中,"$1"/* 应该是"$1"/*/
  • @AntonKovalenko - 是的,打字太快而且没有注意。谢谢,我已经修复了find。重新 for 循环,我给它留下了 if 以使其更接近 OP 的原始代码。两者都可以。
  • @AntonKovalenko 你能解释一下 /*/ 的用途吗
  • *的含义见man bash中的Pathname Expansion。尾随 / 使其仅匹配目录。
【解决方案2】:

统计可执行文件的数量(如标题所说)

 count=0 
 for file in yourdir/*; do 
     if [ -x $file ]; then 
         count=$((count+1)); 
     fi; 
 done; 
 echo "total ${count}"

要计算文件夹,只需将 -x 测试更改为 -d

【讨论】:

  • 是的 - 问题不明确总是让事情变得有趣。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 2015-09-16
  • 1970-01-01
相关资源
最近更新 更多