I'm trying to add filter commands to top for non-interactive usage. While using top, it is possible to specify filters interactively, e.g.
$ top
Type: o
Enter: COMMAND=MyProcess
will show only those processes with "MyProcss" in the command.
Further, top's display settings can be saved to file with "W" from the command line to $HOME/.toprc. Then when top is started again, it will use those display settings instead of the default.
But it seems that filters which are added via "COMMAND=..." are not saved in the .toprc file. So is it possible to add these filters via command line so that top can output the data non-interactively? I can't use top's "-p" option to display data from specific PIDs since I have more than 20 PIDs that need to be tracked, and they could be added after top is invoked. Also, I don't want to output data for all 900+ processes that are running on my machine.
Finally, I don't really want to just grep the process names since I want the header of top as well.
So ideally, the pseudo command would be like, but this doesn't work:
top -b -o 'COMMAND=MyProcess' -o '!COMMAND=NotThisProcess'
I use the "expect" tool to start "top", enter the filtering commands, then let top continue running normally.
#!/usr/bin/env expect
spawn top
expect "COMMAND"
send "O"
expect "add filter"
send "COMMAND=MyProcess\n"
interact
When using expect you typically must wait for some expected output before sending the next keystrokes. I chose COMMAND from the top headers to wait for top to startup, and "add filter" after sending "O" to make sure top is ready for the filtering string. The "interact" command tells expect to keep the command running and pass all input/output through unmodified until the command exits.
Expect is a tcl interpreter, so you could add support for passing command line arguments to the top command while looking for extra filtering arguments and turning those into expect/send sequences. My use case had a fixed command and I didn't need extra options for top, so a hardcoded expect script was all I needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With