Advertisement
metalx1000

Convert File Size Output in Pure BASH

Jan 8th, 2025
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.27 KB | None | 0 0
  1. #!/bin/bash
  2. # Created By Marc Gilligan
  3. # https://github.com/ulfnic
  4. # BSD-0 or CC-0
  5.  
  6. print_size() {
  7.   local -a types=(B KiB MiB GiB TiB PiB EiB ZiB YiB)
  8.   local num=$1
  9.   local \
  10.     num_len=${#num} \
  11.     thousands digits
  12.  
  13.   thousands=$(((num_len - 1) / 3))
  14.   ((thousands >= ${#types[@]})) && return 1
  15.   digits=$((num_len - (thousands * 3) + 1))
  16.  
  17.   if ((thousands > 0)); then
  18.     printf '  %*s%s %s\n' 4 "${num:0:digits}" ".${num:digits:1}" "${types[thousands]}"
  19.   else
  20.     printf '  %*s %s\n' 6 "${num:0:digits}" "${types[thousands]}  "
  21.   fi
  22. }
  23.  
  24. print_size 1
  25. print_size 12
  26. print_size 123
  27. print_size 1234
  28. print_size 12345
  29. print_size 123456
  30. print_size 1234567
  31. print_size 12345678
  32. print_size 123456789
  33. print_size 1234567890
  34. print_size 12345678901
  35. print_size 123456789012
  36. print_size 1234567890123
  37. print_size 12345678901234
  38. print_size 123456789012345
  39. print_size 1234567890123456
  40. print_size 12345678901234567
  41. print_size 123456789012345678
  42. print_size 1234567890123456789
  43. print_size 12345678901234567890
  44. print_size 123456789012345678901
  45. print_size 1234567890123456789012
  46. print_size 12345678901234567890123
  47. print_size 123456789012345678901234
  48. print_size 1234567890123456789012345
  49. print_size 12345678901234567890123456
  50. print_size 123456789012345678901234567
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement