简体   繁体   中英

Bash script to analyze directory and print directory summary

I am working on a script that will analyze any dir in unix and will display the output: script.sh dir1 dir2 ... dirn

Needed output: Directory xxx contains yy files and zz directories

#!/bin/bash
echo 'Enter Dir names'
read dirs
for input_source in $dirs; do 
ls -ld|wc -l; 
echo
# here goes a problem I am trying to figure out how to get this value printed by echo
# together with dirs and files quantity

Please advise.

I am not able to figure out how to proceed with the code. Please advise

Note: Edited to take care of new line in file/dir names.

Better not to parse ls command's output.

To count files (no dirs):

find "$DIR" -maxdepth 1 -type f -exec echo -n . \; | wc -c

To count dirs:

find "$DIR" -maxdepth 1 -type d -exec echo -n . \; | wc -c

Your full script:

#!/bin/bash
echo 'Enter Dir names'
read dirs
for DIR in "$dirs"; do 
    numFiles=$(find "$DIR" -maxdepth 1 -type f -exec echo -n . \; | wc -c)
    numDirs=$(find "$DIR" -maxdepth 1 -type d -exec echo -n . \; | wc -c)
    echo "Directory $DIR contains $numFiles files and $numDirs directories"
done

in your code use the following : @where ls -ld is written

getting directories

  ls -latr | sed -n '/^d/p' zdirlst | grep -v "\." 

getting files :

  ls -latr | sed -n '/^-/p' zdirlst | grep -v "\."

add wc -l to get count and display as per reqd ...

hope this helps !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM