简体   繁体   中英

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. I search for the use of bc , but something is wrong...

You're assigning PorcUsado to scale=2;UsadoMem/TotalMem and then piping the output of that assignment (nothing) into bc . You probably want the pipe inside a command substitution, eg (using a here string instead of a pipe):

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

But you'll also need to evaluate those shell variables - bc can't do it for you:

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

Notice the use of " instead of ' and the $ prefix to allow Bash to evaluate the variables.

Also, if this is the whole script, you can just skip the PorcUsado variable at all and let bc write directly to 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? 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 .

EDIT : Correcting the variable names

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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