Count the number of executable files in bash

前端 未结 2 1607
逝去的感伤
逝去的感伤 2021-01-29 13:07

I have seen a lot of answers about this subject but I don\'t want to do this using find. I have written this but something not working:

function Cou         


        
2条回答
  •  囚心锁ツ
    2021-01-29 13:21

    If your goal is to count directories, there are so many options.

    The find way, which you said you don't want:

    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)
    }
    

    The for way, similar to your example:

    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"
    }
    

    The set way, which skips the loop entirely.

    CountDir() {
      if [[ ! -d "$1" ]]; then
        echo "ERROR: $1 is not a directory." >&2
        return 1
      fi
      set -- "$1"/*/
      echo "Total: $#"
    }
    

提交回复
热议问题