【发布时间】: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 使用率......也很有趣,但不是我所期望的。