如何使用bash将PID的内存使用情况存储在变量中

huangapple go评论53阅读模式
英文:

How to get Memory Usage for a PID in a variable using bash

问题

这是我一直在处理但没有成功的内容,

if [ "$memUsage" -gt "30500" ];
	then
		transUsage=$(pmap 3097 | tail -n 1 | awk '/[0-9]/{print $2}')
		transUsage=$(echo "$transUsage" | awk '/[0-9]/{print $2}') # 这是我试图去除额外的K的尝试
		if [ "$transUsage" -gt "10500" ];
		then
		echo "终止这个和那个"
		fi
	# 打印使用情况
  	echo "内存使用: $memUsage KB"
	fi

我需要将进程ID 3097的内存使用情况存储在变量中,以便我可以使用if命令。
目前它的输出是,

xxxxK,其中x是内存使用大小。由于K是大小的一部分,它没有被识别为数值。

如何解决这个问题?感谢帮助。
致敬!

英文:

This is what I've been working with but haven't been successful,

if [ "$memUsage" -gt "30500" ];
	then
		transUsage=$(pmap 3097 | tail -n 1 | awk '/[0-9]/{print $2}')
		transUsage=$transUsage | awk '/[0-9]/{print $2}' #This was my attempt at removing the extra K
		if [ "$transUsage" -gt "10500" ];
		then
		echo "Terminated this and this"
		fi
	# Print the usage
  	echo "Memory Usage: $memUsage KB"
	fi

I need memory usage of PID 3097 in variable so that I could use if command.
Currently it outputs,

xxxxK, where x is memory usage size. Due to K being part of size, it's not being being recognized as numeric value.

How to solve this? Would appreciate the help.
Regards!

答案1

得分: 1

你可以使用这个更好的代码:

#!/bin/bash

pid=$1

transUsage=$(pmap $pid | awk 'END{sub(/K/, "", $2); print $2}')
if ((transUsage > 10500)); then
    echo "终止这个和那个"
fi

echo "内存使用: $transUsage KB"

`((...))` 是一个算术命令,如果表达式非零则返回退出状态0,如果表达式为零则返回退出状态1。如果需要副作用(赋值),它也可以用作"let"的同义词。请参阅 <http://mywiki.wooledge.org/ArithmeticExpression>。

<details>
<summary>英文:</summary>

You can use this better code:

    #!/bin/bash
    
    pid=$1

    transUsage=$(pmap $pid | awk &#39;END{sub(/K/, &quot;&quot;, $2); print $2}&#39;)
    if ((transUsage &gt; 10500)); then
        echo &quot;Terminated this and this&quot;
    fi

    echo &quot;Memory Usage: $transUsage KB&quot;

`((...))` is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for &quot;let&quot;, if side effects (assignments) are needed. See &lt;http://mywiki.wooledge.org/ArithmeticExpression&gt;.


</details>



huangapple
  • 本文由 发表于 2023年2月18日 16:48:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定