简体   繁体   English

Bash脚本以监听Shell命令输出

[英]Bash Script To Listen For Shell Command Output

Quick question. 快速提问。 How would I go about having a shell script to do the following: 我将如何使用Shell脚本执行以下操作:

  • 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... 执行unix命令(pmset -g ps)每5秒检查一次该脚本的输出,然后如果该命令的输出下降到40%以下(输出示例为:'当前从'AC Power'绘图'-iBox 100%;收费”),然后让它运行Unix shell脚本...

Any help would be much appreciated. 任何帮助将非常感激。

Edit, for Bash 2.05 and later : 针对Bash 2.05 及更高版本进行编辑:

#!/bin/bash
tab=$'\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: 原始,适用于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

这样的事情会起作用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM