Bash提示符中的最高CPU使用率过程

时间:2013-12-06 09:20:34

标签: bash prompt

当我尝试在我的Bash提示符中显示顶级cpu进程时,我遇到以下问题:我得到的信息是动态,我无法获得显着的结果。 我解释一下:我从 top 命令中获取一个字符串,以便在此时立即获取PID,Command和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\\$"
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为你需要一个函数来输出所有东西 - 包括顶部输出和根据长度的东西。

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两次,但每个长度都是正确的。