英文:
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 'END{sub(/K/, "", $2); print $2}')
if ((transUsage > 10500)); then
echo "Terminated this and this"
fi
echo "Memory Usage: $transUsage KB"
`((...))` 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 "let", if side effects (assignments) are needed. See <http://mywiki.wooledge.org/ArithmeticExpression>.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论