Register
It is currently Tue Oct 21, 2014 7:36 pm

Bash script for printing folder names and their sizes


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Fri Oct 25, 2013 10:24 am   

Joined: Fri Oct 25, 2013 9:56 am
Posts: 1
Good day, everyone!

I'm very new to bash scripting. Our teacher gave us a task to create a script that basically does the same job the 'du' command does, with the difference that 'du' command gives an output in the form of
Code:
<size> <folder name>

and what we need is
Code:
<folder name> <size>


As for the moment, I came up with the following script:
Code:
du $1 2> /dev/null |\
   
sort -nr -k1 |\

head -10 |\                    #We need only to show 10 which are the biggest ones

cut -f2  |\

   while read fname

      do

         printf "${fname}\t`du -h --summarize \"$fname\" 2> /dev/null | cut -f1`\n" 

      done


Generally it does what it should, but very-very slow indeed. For example, on my '/usr' folder 'du' command (with everything before 'while' included) works for about 2 minutes and 30 seconds, while the script runs for 7 minutes and 20-30 seconds.

Is there a way to make it work faster? As I wrote before, I'm very new to scripting, so no doubt I'm missing something important.

Thank you for all your help in advance!


Top
 Profile  
 PostPosted: Fri Oct 25, 2013 11:41 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 550
hi,

of course re-doing du takes time.
Code:
#!/bin/bash

mo=$((1024*1024))
while read s n
do
   if ((++x<=10))
   then
      LC_NUMERIC=C printf '%s %.1f Mo\n' "$n" $(bc -l <<< "$s/$mo")
   else
      break
   fi
done < <(du "$1" | sort -nr -k1,1)
printf is to be used to separate format from data, not as a simple echo.


Top
 Profile  
 PostPosted: Wed Nov 06, 2013 2:44 pm   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
Code:
#!/bin/sh

du -h "${1:-.}" | awk -v n="${2:-10}" '
NR <= n {
    dirs[$1] = $2
    if ((l = length($2)) > max_len)
        max_len = l
}
END {
    for (d in dirs)
        printf "%s %*s\n", dirs[d], max_len - length(dirs[d]) + length(d), d
}'

Haha!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP