shell脚本中将字节转化为B,KB,GB类型shell脚本中将字节转化为B,KB,GB类型
1. 重点处理
1.1 判断输⼊是否为数字
totalsize=$1
if [[ "$totalsize" =~ ^[0-9]+$ ]] # 正则匹配0-9
then echo "is a number"
else
echo "null"
fi
1.2 做保留⼩数位的除法
# 此处为计算总⼤⼩除以1024并且保留三位⼩数。
# 其中scale=3 为保留三位⼩数,totalsize 为输⼊的数字。
size=`echo  "scale=3; a = $totalsize / 1024 ;
if (length(a)==scale(a)) print 0;print a"  | bc `
2. 将字节处理为KB,MB,GB
if [ 1024 -gt $totalsize ];
then size="$totalsize"B
elif [ 1048576 -gt $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1024 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"KB
elif [ 1073741824 -gt $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1048576 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"MB
elif [ 1073741824 -le $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1073741824 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"GB
else
shell最简单脚本size="0"
fi
3. 总体代码
#!/bin/bash
totalsize=$1
if [[ "$totalsize" =~ ^[0-9]+$ ]];
then
if [ 1024 -gt $totalsize ];
then size="$totalsize"B
elif [ 1048576 -gt $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1024 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"KB
elif [ 1073741824 -gt $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1048576 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"MB
elif [ 1073741824 -le $totalsize ];
then
size=`echo  "scale=3; a = $totalsize / 1073741824 ; if (length(a)==scale(a)) print 0;print a"  | bc `
size="$size"GB
else
size="0"
fi
else
size="NULL"
fi
echo $size
4. 测试结果和总结
总结:在java和python中,字节转为KB之类的较为简单,但是由于shell脚本的特殊性,此时实现需要综合考虑shell脚本内的⼀些格式,其实最重要的⼀点,就是如何计算除法并且保留⼩数位。