duse 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/bin/bash
  2. USAGE="Usage: duse [ base_dir ]
  3. \tdisplay the disk space usage of the specified directory and each immediate subdirectory\n"
  4. COL_W=8
  5. if [ "$1" == "" ] ; then base_dir=`pwd` ;
  6. elif [ ! -d "$1" ] ; then printf "$USAGE" ; exit ;
  7. else base_dir=$1 ; fi ;
  8. # get absolute path
  9. path=`realpath "$base_dir" 2> /dev/null`
  10. if [ "$path" == "" ] ; then path=$base_dir ; fi
  11. # get results
  12. while read line
  13. do
  14. free_mb="$( echo $line | cut -d ' ' -f 1)" ; free_mbs=( ${free_mbs[@]} "$free_mb" ) ;
  15. dir_name="$(echo $line | cut -d ' ' -f 2)" ; dir_names=( ${dir_names[@]} "$dir_name" ) ;
  16. total_dir_free_mb=$(( $total_dir_free_mb + $free_mb ))
  17. done < <(du "$base_dir" --max-depth=1 --block-size=1 | sort -n)
  18. # compute base dir use
  19. n_dirs=${#dir_names[@]}
  20. free_mbs[$n_dirs]=${free_mbs[$(( $n_dirs - 1 ))]}
  21. dir_names[$n_dirs]="${dir_names[$(( $n_dirs - 1 ))]}/* (total)"
  22. total_free_mb=${free_mbs[$n_dirs]}
  23. base_dir_free_mb=$(( $total_free_mb - $(( $total_dir_free_mb - $total_free_mb )) ))
  24. free_mbs[$(( $n_dirs - 1 ))]=$base_dir_free_mb
  25. n_dirs=$(( $n_dirs + 1 ))
  26. # display directory usage
  27. printf "directory sizes under '$path'\n"
  28. printf "MB used | dir\n"
  29. printf "%s\n" "--------|----"
  30. for (( dir_n=0 ; dir_n<$n_dirs ; dir_n++ ))
  31. do
  32. free_mb=$(( ${free_mbs[$dir_n]} / 1024 / 1024 ))
  33. dir_name=${dir_names[$dir_n]}
  34. pad_w=$(( $COL_W - ${#free_mb} ))
  35. printf "%s%${pad_w}s| used in %s\n" "$free_mb" "" "$dir_name"
  36. done
  37. # display per partition free space
  38. printf "\nfree space per partition\n"
  39. printf "MB free | partition\n"
  40. printf "%s\n" "--------|----------"
  41. while read line
  42. do
  43. device=`echo $line | awk '{ print $1 }'`
  44. free_mb=`echo $line | awk '{ print $4 }'`
  45. percent=`echo $line | awk '{ print $5 }'`
  46. mountpoint=`echo $line | awk '{ print $6 }'`
  47. pad_w=$(($COL_W - ${#free_mb}))
  48. printf "%s%${pad_w}s| %s free on %s => %s\n" $free_mb "" $percent $device $mountpoint
  49. done < <(df --type=ext4 --block-size=1M | grep -v Avail)