【问题标题】:Top CPU usage process in Bash promptBash 提示符中 CPU 使用率最高的进程
【发布时间】:2013-12-06 09:20:34
【问题描述】:

当我尝试在我的 Bash 提示符中显示顶级 cpu 进程时,我遇到了以下问题:我得到的信息是如此 动态,以至于我无法获得显着的结果。 我解释一下:我从 top 命令中获取一个字符串,以获取此时使用率最高的进程的 PID、命令和 CPU%。这存储在 $topcpuS 变量中。

然后我想知道这个字符串的长度(比如${#topcpuS}),来调整我在提示中的显示。 问题 : 在我捕获字符串的那一刻和我想要获取它的长度的那一刻之间,内容已经改变了 - 所以长度与$topcpuS的实际内容不匹配...

当我在 PS1 中显示 $topcpuS 两次时显示证据:内容不同。

我想我做错了什么。

我的 Bash 脚本摘要(脚本调用:source /path/to/myscript ; ps1_test):

ps1_test() {
  ## Function used to get string length, by ignoring escape sequence
  ## for ANSI color or UNICODE special characters
  ## Usage :   count_char "$my_string"
  count_char() {
      local xcc=$(echo "$1" | sed -r 's/((\\\\\[)?\\[eE]\[[0-9]*(;[0-9]*)*(m|f)(\\\\\])?|\\u1F6(0|1|3)|\\u[0-9a-fA-F]{3}|\\xf0\\x9f\\x98\\x(8|9|b)|(\\x[0-9a-fA-F]{2}){2}\\x[0-9a-fA-F])//g')
      printf '%u' ${#xcc}
  }  ## END count_char

  ## Get top process
  local topcpuS=" \$(top -bn1 | tail -n +8 | sort -nrk 9 | awk 'NR==6 {printf(\"[%s]%s:%s%\",\$1,\$12,\$9)}') "
  ## Get length of topcpuS
  local topcpuL="\$(count_char \"$topcpuS\")"
  ## DISPLAY PROMPT (with topcpuS called twice...)
  PS1="\n$TOP >${topcpuS}< [Length:${topcpuL}]\n$TOP >${topcpuS}< [Length:${topcpuL}]\n\\$"
}

感谢您的帮助!

【问题讨论】:

  • ps aux | sort -r -k 3 | head -n 5 ?
  • 或使用ps -e -opcpu=,cmd= | sort -r -k1 | sed -n 's/ *[^ ]* *//p;q'
  • 嗨,谢谢。我不想使用 PS,因为您没有“即时”CPU 使用情况的快照。相反,PS 为您提供了一个进程的总体 CPU 使用率......也很有趣,但不是我所期望的。

标签: bash prompt


【解决方案1】:

我认为您需要一个函数来输出所有内容 - 顶部输出和取决于长度的内容。

ps1_test() {
  ## Function used to get string length, by ignoring escape sequence
  ## for ANSI color or UNICODE special characters
  ## Usage :   count_char "$my_string"
  count_char() {
      local xcc=$(echo "$1" | sed -r 's/((\\\\\[)?\\[eE]\[[0-9]*(;[0-9]*)*(m|f)(\\\\\])?|\\u1F6(0|1|3)|\\u[0-9a-fA-F]{3}|\\xf0\\x9f\\x98\\x(8|9|b)|(\\x[0-9a-fA-F]{2}){2}\\x[0-9a-fA-F])//g')
      printf '%u' ${#xcc}
  }  ## END count_char

  top_stuff() {
        local topcpuS=$(top -bn1 | tail -n +8 | sort -nrk 9 | awk 'NR==6 {printf("[%s]%s:%s%",$1,$12,$9)}')
        local topcpuL=$(count_char "$topcpuS")
        echo ">${topcpuS}< [Length:${topcpuL}]"
  }

  ## DISPLAY PROMPT (with topcpuS called twice...)
  PS1="\n$TOP \$(top_stuff)\n$TOP \$(top_stuff)\n\\$"
}

这将调用top_stuff 两次,但每个长度都是正确的。

【讨论】:

  • 确实解决了长度问题。通过 2 次 top_stuff 调用,您将获得 2 个不同的结果。但至少,长度是正确的。
猜你喜欢
  • 2010-09-08
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多