简体   繁体   English

bash脚本中的除法

[英]Division in bash script

I have the following script: 我有以下脚本:

#!/bin/bash
TotalMem=$(top -n 1 | grep Mem | awk 'NR==1{print $4}') #integer
UsadoMem=$(top -n 1 | grep Mem | awk 'NR==1{print $8}') #integer
PorcUsado='scale=2;UsadoMem/TotalMem'|bc -l 
echo $PorcUsado

The variable PorcUsado returns empty. 变量PorcUsado返回空。 I search for the use of bc , but something is wrong... 我在寻找使用bc ,但是出了点问题...

You're assigning PorcUsado to scale=2;UsadoMem/TotalMem and then piping the output of that assignment (nothing) into bc . 您正在将PorcUsado分配为scale=2;UsadoMem/TotalMem ,然后将该分配的输出( scale=2;UsadoMem/TotalMem )输送到bc You probably want the pipe inside a command substitution, eg (using a here string instead of a pipe): 您可能希望在命令替换中使用管道,例如(使用here字符串而不是管道):

PorcUsado=$(bc -l <<<'scale=2;UsadoMem/TotalMem')

But you'll also need to evaluate those shell variables - bc can't do it for you: 但您还需要评估这些shell变量bc不能为您做到这一点:

PorcUsado=$(bc -l <<<"scale=2;$UsadoMem/$TotalMem")

Notice the use of " instead of ' and the $ prefix to allow Bash to evaluate the variables. 注意,使用"代替'$前缀来允许Bash评估变量。

Also, if this is the whole script, you can just skip the PorcUsado variable at all and let bc write directly to stdout. 另外,如果这是整个脚本,则可以完全跳过PorcUsado变量,然后让bc直接写入stdout。


#!/bin/bash
TotalMem=$(top -n 1 | grep Mem | awk 'NR==1{print $4}') #integer
UsadoMem=$(top -n 1 | grep Mem | awk 'NR==1{print $8}') #integer
bc -l <<<"scale=2;$UsadoMem/$TotalMem"

Why pipe top output at all? 为什么要管top输出呢? Seems too costly. 似乎太昂贵了。

$ read used buffers < <(
    awk -F':? +' '
      {a[$1]=$2}
      END {printf "%d %d", a["MemTotal"]-a["MemFree"], a["Buffers"]}
    ' /proc/meminfo
  )

Of course, it can easily be a one-liner if you value brevity over readability. 当然,如果您重视简洁而不是可读性,那么它很容易成为一线客。

I think the pipe is the problem try something like this: 我认为管道是问题,请尝试以下操作:

PorcUsado=$(echo "scale=2;$UsadoMem/$TotalMem" | bc -l) 

i haven't tested it yet but you have to echo the string and pipe the result from echo to bc . 我还没有测试过,但是您必须回显字符串并将结果从echo发送到bc

EDIT : Correcting the variable names 编辑 :更正变量名称

您不需要grepbc ,因为awk可以自己搜索和做数学运算:

top -n 1 -l 1 | awk '/Mem/ {printf "%0.2f\n",$8/$4;exit}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM