将一行"top"、"htop"或"intel_gpu_top"



我想将top输出的1行保存到Bash数组中,以便稍后访问其组件:

$ timeout 1 top -d 2 | awk 'NR==8'
2436 USER       20   0 1040580 155268  91100 S   6.2   1.0  56:38.94 Xorg
Terminated 

我试过了:

$ gpu=($(timeout 1s top -d 2 | awk 'NR==8'))
$ mapfile -t gpu < <($(timeout 1s top -d 2 | awk 'NR==8'))

并且,偏离阵列必要条件,甚至:

$ read -r gpu < <(timeout 1s top -d 2 | awk 'NR==8')

对于CCD_ 2(前两个(或CCD_。

编辑:
正如@Cyrus等人所指出的,gpu=($(top -n 1 -d 2 | awk 'NR==8'))是显而易见的解决方案。然而,我想动态地构建cmd,以便top -d 2可以被其他cmd(如htop -d 20intel_gpu_top -s 1(所取代。只有top可以限制其最大迭代次数,因此这通常不是一个选项,因此我在所有显示的尝试中都使用timeout 1s来终止进程
结束编辑

使用Bash以外的shell是而不是选项。为什么上述尝试失败了,我该如何做到这一点?

为什么上述尝试未通过

由于重定向到管道不具有终端功能,top进程在尝试写入终端并获取终端时接收到SIGTTOU信号";背面";从外壳中取出。该信号导致top终止。

我该如何实现这一点?

使用top -n 1。通常,使用特定于工具的选项来禁用该工具使用终端实用程序。

然而,我想动态构建cmd,以便top-d 2可以被其他cmd取代,如htop-d 20或intel_gpu_top-s 1

编写自己的终端仿真,并从命令显示的第一个填充的缓冲区中提取第一行。有关灵感,请参阅GNUscreentmux源代码。

如果要退出top,我认为您不需要暂停。你可以使用-n和-b标志,但如果你需要,可以随意添加

#!/bin/bash
arr=()
arr[0]=$(top -n 1 -b -d 2 | awk 'NR==8')
arr[1]=random-value
arr[2]=$(top -n 1 -b -d 2 |awk 'NR==8')
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}
output:
1 root 20 0 99868 10412 7980 S 0.0 0.5 0:00.99 systemd
random-value
1 root 20 0 99868 10412 7980 S 0.0 0.5 0:00.99 systemd

来自顶部手册页:

-b  :Batch-mode operation
Starts top in Batch mode, which could be useful for sending output from top to other  programs  or  to  a
file.   In  this  mode, top will not accept input and runs until the iterations limit you've set with the
`-n' command-line option or until killed.
-n  :Number-of-iterations limit as:  -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.
-d  :Delay-time interval as:  -d ss.t (secs.tenths)
Specifies the delay between screen updates, and overrides  the  corresponding  value  in  one's  personal
configuration  file  or  the  startup default.  Later this can be changed with the `d' or `s' interactive
commands.

最新更新