Count files and directories using shell script

后端 未结 5 603
悲&欢浪女
悲&欢浪女 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
    
    0 讨论(0)
  • 2021-01-01 19:42

    You're not iterating over the list of files inside the given directory; add /* after $LOCATION. Your script should look like:

    ...
    for item in $LOCATION/*
    do
    ...
    

    As pointed by dogbane, just adding /* will count only files that does not begin with .; for doing so, you shall do the following:

    ...
    for item in $LOCATION/* $LOCATION/.*
    do
    ...
    
    0 讨论(0)
  • 2021-01-01 19:44

    Use

    find $LOCATION -maxdepth 1 -type f | wc -l
    

    For the count of files, and

    find $LOCATION -maxdepth 1 -type d | wc -l
    

    For counting directories

    0 讨论(0)
  • 2021-01-01 19:45

    Use find as shown below. This solution will count filenames with spaces, newlines and dotfiles correctly.

    FILECOUNT="$(find . -type f -maxdepth 1 -printf x | wc -c)"
    DIRCOUNT="$(find . -type d -maxdepth 1 -printf x | wc -c)"
    

    Note that the DIRCOUNT includes the current directory (.). If you do not want this, subtract 1.

    ((DIRCOUNT--)) # to exclude the current directory
    
    0 讨论(0)
  • 2021-01-01 19:45

    ... am wondering if there is a simpler way of doing it.

    If you say so ;)

    Alternatively, reduce your script to

    find /path/to/directory | wc -l
    

    For current directory, do:

    find . | wc -l
    
    0 讨论(0)
提交回复
热议问题