Count files and directories using shell script

后端 未结 5 638
悲&欢浪女
悲&欢浪女 2021-01-01 18:49

I\'m learning bash scripting and have written a script to count the files and directories in the directory that is supplied as argument. I have it working one way which seem

5条回答
  •  失恋的感觉
    2021-01-01 19:36

    To just solve the problem you can use:

    FILECOUNT=$(find $LOCATION -type f | wc -l)
    DIRCOUNT=$(find $LOCATION -type d | wc -l)
    

    find will look for all files (-type f) or directories (-type d) recursively under $LOCATION; wc -l will count the number of lines written to stdout in each case.

    However if you want to learn, the bash script may be a better way. Some comments:

    • If you want to look for files/directories in $LOCATION only (not recursively under their subdirectories etc), you can use for item in $LOCATION/*, where the * will expand to the list of files/directories in the $LOCATION directory. The missing * is why your original script returns 0/1 (becasue the $LOCATION directory itself is the only item counted).
    • You may want to check first that $LOCATION is actually a directory with [ -d $LOCATION ].
    • For arithmetic expressions, use $(( ... )), for example FILECOUNT=$(( FILECOUNT + 1 )).
    • If you want to find all files/directories recursively, you could combine find with a loop.

    Example:

    find $LOCATION | while read item; do
        # use $item here...
    done
    

提交回复
热议问题