Shell Script To Provide ls -l in output in customized format

by on October 20, 2008 · 3 comments

  1. #!/bin/bash
  2. #Write the shell program which produces a report from the output of ls -l in the following format
  3. # file1
  4. # file2
  5. # [DIR] test/
  6. # Total regular files : 7
  7. # Total directories : 4
  8. # Total symbolic links : 0
  9. # Total size of regular files : 2940
  10. # --------------------------------------------------------------------
  11. # This is a free shell script under GNU GPL version 2.0 or above
  12. # Copyright (C) 2005 nixCraft project.
  13. # Feedback/comment/suggestions : http://cyberciti.biz/fb/
  14. # -------------------------------------------------------------------------
  15. # This script is part of nixCraft shell script collection (NSSC)
  16. # Visit http://bash.cyberciti.biz/ for more information.
  17. # -------------------------------------------------------------------------
  18. rf=0
  19. dir=0
  20. syml=0
  21. totsize=0
  22. output=""
  23. for f in *
  24. do
  25. if [ -f $f ]
  26. then
  27. output=$f
  28. ((rf++))
  29. size=$(ls -l "${f}" | awk '{ print $5}')
  30. totsize=$((totsize+size))
  31. fi
  32. if [ -d $f ]
  33. then
  34. output="[DIR] $f/"
  35. ((dir++))
  36. fi
  37. if [ -L $f ]
  38. then
  39. output="[LINK] $f@"
  40. ((syml++))
  41. fi
  42. echo $output
  43. done
  44.  
  45. echo "Total regular files : $rf"
  46. echo "Total directories : $dir"
  47. echo "Total symbolic links : $syml"
  48. echo "Total size of regular files : $totsize"


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • jo

    nixcraft site is absolutely such a helpful site to me.
    its very user friendly especially to those who are newbie in linux like me.
    easy to understand and gives a good example. thanks to nixcraft!!

  • Hamid Noroozi

    Hi
    there is a problem with your script
    when you execute it , if there is any file or directory which it’s name contains ” ” ( i mean space ) , you would get some error.
    to deal this error you should modify all your if clause to :
    if [ -f “$f” ]
    another note is that , we expect a “ls” comand to accept an argument as a path , for example : ls /etc/ —> should list all the files and directories in /etc/.
    to deal this i suggest you to modify these lines :
    output=””
    cd “$1″ ##this line is added between the 2 lines you had##
    for f in *
    .
    .
    .
    echo “Total size of regular files : $totsize”
    cd “-” > /dev/null ## and this line is added at the end of script##
    ——————
    thnx for your nice ideas in scripting


    Best Regards , H.Noroozi

  • Nt

    Thanks a lot for all these examples. Very useful to learn shell scripts for a newbie like me :)

Previous Script:

Next Script: