How to get the number of files in a folder as a variable?

前端 未结 10 1259
粉色の甜心
粉色の甜心 2020-12-28 13:21

Using bash, how can one get the number of files in a folder, excluding directories from a shell script without the interpreter complaining?

With the help of a friend

相关标签:
10条回答
  • 2020-12-28 14:12

    The most straightforward, reliable way I can think of is using the find command to create a reliably countable output.

    Counting characters output of find with wc:

    find . -maxdepth 1 -type f -printf '.' | wc --char
    

    or string length of the find output:

    a=$(find . -maxdepth 1 -type f -printf '.')
    echo ${#a}
    

    or using find output to populate an arithmetic expression:

    echo $(($(find . -maxdepth 1 -type f -printf '+1')))
    
    0 讨论(0)
  • 2020-12-28 14:13

    Get rid of the quotes. The shell is treating them like one file, so it's looking for "ls -l".

    0 讨论(0)
  • 2020-12-28 14:20

    Simple efficient method:

    #!/bin/bash
    RES=$(find ${SOURCE} -type f | wc -l)
    
    0 讨论(0)
  • 2020-12-28 14:20

    Here's one way you could do it as a function. Note: you can pass this example, dirs for (directory count), files for files count or "all" for count of everything in a directory. Does not traverse tree as we aren't looking to do that.

    function get_counts_dir() {
    
        # -- handle inputs (e.g. get_counts_dir "files" /path/to/folder)
        [[ -z "${1,,}" ]] && type="files" || type="${1,,}"
        [[ -z "${2,,}" ]] && dir="$(pwd)" || dir="${2,,}"
    
        shopt -s nullglob
        PWD=$(pwd)
        cd ${dir}
    
        numfiles=(*)
        numfiles=${#numfiles[@]}
        numdirs=(*/)
        numdirs=${#numdirs[@]}
    
        # -- handle input types files/dirs/or both
        result=0
        case "${type,,}" in
            "files")
                result=$((( numfiles -= numdirs )))
            ;;
            "dirs")
                result=${numdirs}
            ;;
            *)  # -- returns all files/dirs
                result=${numfiles}
            ;;
    
        esac
    
        cd ${PWD}
        shopt -u nullglob
    
        # -- return result --
        [[ -z ${result} ]] && echo 0 || echo ${result}
    }
    

    Examples of using the function :

    folder="/home"
    get_counts_dir "files" "${folder}"
    get_counts_dir "dirs" "${folder}"
    get_counts_dir "both" "${folder}"
    

    Will print something like :

    2
    4
    6
    
    0 讨论(0)
提交回复
热议问题