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

前端 未结 10 1409
粉色の甜心
粉色の甜心 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: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
    

提交回复
热议问题