【问题标题】:bash - using recursion - counting the executable files in dirbash - 使用递归 - 计算目录中的可执行文件
【发布时间】:2015-01-31 11:34:08
【问题描述】:

我不是在寻找一些高级别的答案,只有一行,我正在尝试制作一个可以工作的脚本,并使其与递归一起工作并理解它:)

我正在尝试学习 bash 脚本,但遇到了一些问题:

我正在尝试计算目录及其子目录中可执行文件的数量

这就是我的想法

文件名countFiles:

#!/bin/bash
counter = 0
for FILE in ($1/*)  /// going over all the files in the input path
do
 if (-d $FILE); then        /// checking if dir
  ./countFiles $FILE  /// calling the script again with ned path
  counter= $($counter + $0) /// addint to the counter the number of exe files from FILE
 fi
 if (-f $FILE); then /// checking if file
  if (-x $FILE); then /// checking id exe file
   counter = $counter + 1 // adding counter by 1
  fi
 fi
done
exit($counter) // return the number for exe files

【问题讨论】:

  • 这不是 Bash!现在,这不行吗? find . -type f -exec sh -c 'for i; do [ -x "$i" ] && printf 1; done' _ {} \; | wc -c
  • 是的,它可以工作,但我正在尝试制作一个易于理解的脚本并制作类似的脚本
  • 呃...为什么不find . -type f -executable | wc -l?
  • @Wintermute:因为在文件名包含换行符的情况下(可能不太可能)失败:touch $'a\nb'; chmod +x $'a\nb'; find . -type f -executable | wc -l。 -executable 也不是 POSIX(我猜它只在 GNU find 中可用)。除此之外,你的命令很好。
  • @gniourf_gniourf 是的,好的。我猜贝壳产卵只是以错误的方式摩擦我。也许find . -type f -exec test -x '{}' \; -printf 1 | wc -c? -exec 是毕竟只是另一个过滤器。

标签: bash shell recursion


【解决方案1】:

如果你真的想使用递归(这在 Bash 中是个坏主意):首先,不要递归调用你的脚本。相反,递归调用函数。这将更有效率(没有分叉开销)。尝试修正你的语法:

#!/bin/bash

shopt -s nullglob

count_x_files() {
   # Counts number of executable (by user, regular and non-hidden) files
   # in directory given in first argument
   # Return value in variable count_x_files_ret
   # This is a recursive function and will fail miserably if there are
   # too deeply nested directories
   count_x_files_ret=0
   local file counter=0
   for file in "$1"/*; do
      if [[ -d $file ]]; then
         count_x_files "$file"
         ((counter+=count_x_files_ret))
      elif [[ -f $file ]] && [[ -x $file ]]; then
         ((++counter))
      fi
   done
   count_x_files_ret=$counter
}

count_x_files "$1"
echo "$count_x_files_ret"

【讨论】:

  • 如果您解释为修复他的语法错误所做的所有更改,将会更有帮助。仅仅发布一个正确的脚本并不能帮助人们理解csh 和bash 语法之间的所有区别。
  • @Barmar:正在等待 OP 询问有关具体点的问题。解释所有的差异似乎是一项艰巨的任务!我想 OP 通过比较他的帖子和我的答案可以看到一些重要的事情。如果您能想到要添加的非常重要的内容,请随时编辑我的帖子!
  • 你不仅仅是在为 OP 写作,你还在为将来阅读这个问题的任何人写一个答案。
  • @Barmar:是的。现在,你让我感觉很糟糕:(。不过,解释东西的任务似乎太大了,而它所带来的回报却很小。这个问题不会有大量的观点,我觉得没有必要补充我的答案。如果将来我看到很多人都在看它,或者如果我的答案质量低劣而遭到太多反对,我可能会考虑添加一些解释。
  • 它真的自我解释了,我只读了 20 遍 int,一些逻辑和它都可以理解 :)
猜你喜欢
  • 2012-02-27
  • 2014-03-30
  • 1970-01-01
  • 2019-09-03
  • 2015-03-01
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多