在shell脚本中使用“du”的输出进行数学运算(需要删除后缀)

时间:2017-12-01 15:37:21

标签: shell bc du

我有这个代码

strg=`du -s -BM /path/folder` 
dstrg=5120 
num=`expr $dstrg -$strg`
num1=`echo $num\* 100 |bc`
num2=`echo $num1/5120 |bc`
echo $num2

我得到变量strg mb处的文件夹用法然后 我想用它将它从5gb的可用空间中删除 但我得到语法错误

1 个答案:

答案 0 :(得分:0)

如果整数结果足够,您甚至不需要bc - 并且在任何情况下都不建议将expr用于现代shell:

#!/usr/bin/env bash
#              ^^^^- ensure that bash extensions are available

declare -- strg=$'4096M\t/path/folder'  # possible result of strg=$(du -s -BM /path/folder)

strg=${strg%%M*}   # delete everything after the first M in the string, inclusive

dstrg=5120

num=$(( ( (dstrg - strg) * 100) / 5120 ))
echo "$num"

...正确发出20作为输出。

请参阅: