在 shell 脚本中使用 "du" 的数学输出(需要去除后缀)
Using the output of "du" for math in a shell script (need to strip suffix)
我有这个代码
strg=`du -s -BM /path/folder`
dstrg=5120
num=`expr $dstrg -$strg`
num1=`echo $num\* 100 |bc`
num2=`echo $num1/5120 |bc`
echo $num2
我在 mb 处获取变量 strg 文件夹使用情况,然后
我想用它从可用的 space 中删除它,即 5gb
但是我遇到了语法错误
如果一个整数结果就足够了,你甚至不需要 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
作为输出。
参见:
- Parameter expansion -- the syntax used in
${strg%%M*}
. Also see BashFAQ #100,一般描述 bash 中的字符串操作。
- Arithmetic expansion -- 描述
$(( ))
,现代语法(适用于与 1991 POSIX sh 标准兼容的所有 shell)替换 expr
.
我有这个代码
strg=`du -s -BM /path/folder`
dstrg=5120
num=`expr $dstrg -$strg`
num1=`echo $num\* 100 |bc`
num2=`echo $num1/5120 |bc`
echo $num2
我在 mb 处获取变量 strg 文件夹使用情况,然后 我想用它从可用的 space 中删除它,即 5gb 但是我遇到了语法错误
如果一个整数结果就足够了,你甚至不需要 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
作为输出。
参见:
- Parameter expansion -- the syntax used in
${strg%%M*}
. Also see BashFAQ #100,一般描述 bash 中的字符串操作。 - Arithmetic expansion -- 描述
$(( ))
,现代语法(适用于与 1991 POSIX sh 标准兼容的所有 shell)替换expr
.