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

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

    Expanding on the accepted answer (by Dennis W): when I tried this approach I got incorrect counts for dirs without subdirs in Bash 4.4.5.

    The issue is that by default nullglob is not set in Bash and numdirs=(*/) sets an 1 element array with the glob pattern */. Likewise I suspect numfiles=(*) would have 1 element for an empty folder.

    Setting shopt -s nullglob to disable nullglobbing resolves the issue for me. For an excellent discussion on why nullglob is not set by default on Bash see the answer here: Why is nullglob not default?

    Note: I would have commented on the answer directly but lack the reputation points.

提交回复
热议问题