Skip to content
Advertisement

Shell Script – Print directories/files & file numbers

I’m trying to write a shell which can print the directories & files in it. I want to add number (for loop) to files in it, but having issues – can you experts look into it and help me out? Thanks

#!/bin/sh

BDIR=$1

rm dir.log

counter(){
        for file in "$1"/*; do
                if [ -d "$file" ]; then
                        echo "$file"
                        counter "$file"
                fi
        done
}

counter "$BDIR" > dir.log

while read -r line; do
        echo  "n Directory Name => $line"
        echo  " This Directory has following File in it...."
        pfile=`ls -l $line/ | awk 'NR>1{print " ==> " $9;}'`
        cnt=`ls -l $line/ | awk 'NR>1{print $9;}' | wc -l`
        for i in $cnt; do
                echo  "$i.      $pfile"
        done
done < dir.log

### Output

    $ ./dr5.sh /home/test
    
     Directory Name => /home/test/scripts
     This Directory has following File in it....
    3.       ==> d_name.sh  ----------> should have 1
     ==> test1  -------------> should have 2
     ==> test2  -------------> should have 3
    
     Directory Name => /home/test/test
     This Directory has following File in it....
    1.       ==> one
    
     Directory Name => /home/test/test/one
     This Directory has following File in it....
    1.       ==> t.sh

Advertisement

Answer

Solved – Updated while loop with following – was simple than anticipated 🙂

    cd $line
    ls -l | awk 'NR>1{print " => " $9}' > cnt.txt
    cat --number cnt.txt
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement