用于监听 Shell 命令输出的 Bash 脚本

发布于 2024-10-19 11:17:24 字数 190 浏览 3 评论 0原文

快问。我将如何让一个 shell 脚本执行以下操作:

  • 执行 unix 命令 (pmset -g ps) 每 5 秒检查该脚本的输出,然后如果该命令的输出下降到 40% 以下(例如输出为:“从‘交流电源’汲取的电流 -易宝100%;充电'),然后让它运行 unix shell 脚本...

任何帮助将不胜感激。

Quick question. How would I go about having a shell script to do the following:

  • execute unix command (pmset -g ps) to check the output of that script every 5 seconds, and then if the output of that command falls to below say 40% (example of output is: 'Currenty drawing from 'AC Power'
    -iBox 100%; charging'), then for it to run a unix shell script...

Any help would be much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挖鼻大婶 2024-10-26 11:17:24

编辑,对于 Bash 2.05 及更高版本

#!/bin/bash
tab=

原始,对于 Bash 3.2 及更高版本:

#!/bin/bash
pattern='[0-9]+'    # works if there's only one sequence of digits in the output, a more selective pattern is possible if needed
while true  # run forever, change to stop on some condition
do
    threshold=100
    until (( threshold < 40 ))
    do
        sleep 5
        result=$(pmset -g ps)
        [[ $result =~ $pattern ]]
        threshold=${BASH_REMATCH[1]}
    done
    shell_script
done
\t' while true # run forever, change to stop on some condition do threshold=100 until (( threshold < 40 )) do sleep 5 result=$(pmset -g ps) threshold="${result#*iBox$tab}" threshold="${threshold%\%*}" done shell_script done

原始,对于 Bash 3.2 及更高版本:

Edit, for Bash 2.05 and later:

#!/bin/bash
tab=

Original, for Bash 3.2 and later:

#!/bin/bash
pattern='[0-9]+'    # works if there's only one sequence of digits in the output, a more selective pattern is possible if needed
while true  # run forever, change to stop on some condition
do
    threshold=100
    until (( threshold < 40 ))
    do
        sleep 5
        result=$(pmset -g ps)
        [[ $result =~ $pattern ]]
        threshold=${BASH_REMATCH[1]}
    done
    shell_script
done
\t' while true # run forever, change to stop on some condition do threshold=100 until (( threshold < 40 )) do sleep 5 result=$(pmset -g ps) threshold="${result#*iBox$tab}" threshold="${threshold%\%*}" done shell_script done

Original, for Bash 3.2 and later:

二智少女猫性小仙女 2024-10-26 11:17:24

像这样的东西会起作用

pmset -g ps | perl -pe 'if(/%.*Ibox ([0-9]+)%; ch.*$/ and $1 < 40){system "nameofshellscript"}'

Something like this would work

pmset -g ps | perl -pe 'if(/%.*Ibox ([0-9]+)%; ch.*$/ and $1 < 40){system "nameofshellscript"}'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文