shell 自动计算 bytes KB MB

自动计算 bytes 为 KB、MB、GB、TB,代码分2种,一种显示整数,一种显示2位小数。

#!/bin/sh
human_bytes(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} Bytes && break
  KB=$(((B+512)/1024))
  [ $KB -lt 1024 ] && echo ${KB} KiB && break
  MB=$(((KB+512)/1024))
  [ $MB -lt 1024 ] && echo ${MB} MiB && break
  GB=$(((MB+512)/1024))
  [ $GB -lt 1024 ] && echo ${GB} GiB && break
  echo $(((GB+512)/1024)) TiB
done
}

human_bytes_2(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} Bytes && break
  KB=$(echo "scale = 2; $B/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$KB > 1024" | bc) -eq 0 ] && echo ${KB} KiB && break
  
  MB=$(echo "scale = 2; $KB/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$MB > 1024" | bc) -eq 0 ] && echo ${MB} MiB && break
  
  GB=$(echo "scale = 2; $MB/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$GB > 1024" | bc) -eq 0 ] && echo ${GB} GiB && break
  
  echo $(echo "scale = 2; $GB/1024" | bc | awk '{printf "%.2f", $0}') TiB
done
}

添加新评论