使用 pgrep 而不是 ps 获取内存使用百分比

Get memory percentage usage using pgrep and not ps

我有一个 bash 脚本,它使用 ps 命令获取内存百分比,如下所示:

g_var_mem=$(ps -aux | grep myproc | grep -v grep | awk '{print }')

我的特定过程的输出是 0.3。

当我使用 ShellCheck 检查脚本时,我收到一条 SC2009 消息,说明 "Consider using pgrep instead of grepping ps output.".

有没有办法使用 pgrep 来获取这个内存百分比?或者另一种方法可以消除此警告?

恕我直言,您不需要使用 2 次 grepawk,而是使用单个 awk

ps -aux | awk '!/awk/ && /your_process_name/{print }'

上面代码的解释:

ps -aux | awk '                      ##Running ps -aux command and passing its output to awk program here.
!/awk/ && /your_process_name/{       ##Checking condition if a line NOT having string awk AND check string(which is your process name) if both conditions are TRUE then do following.
  print                            ##Printing 4th field of the current line here.
}'                                   ##Closing condition BLOCK here.

您也可以这样做:

ps -p $(pgrep YOURPROCESSNAME) -o '%mem='

此致!