Count the number of executable files in bash

2019-03-07 01:21发布

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

I am using this script like the following:

yaser.sh -x './..../...../.....'

The shell runs it and then it outputs: The number of executable files in this dir is: 0 when there is many executable files in this directory.

2条回答
萌系小妹纸
2楼-- · 2019-03-07 01:33

To count the number of executable (like the title says)

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

To count folders, just change the -x test with -d

查看更多
相关推荐>>
3楼-- · 2019-03-07 01:52

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: $#"
}
查看更多
登录 后发表回答