Bash脚本侦听Shell命令输出

时间:2011-02-27 19:20:06

标签: macos bash shell

快速提问。我将如何使用shell脚本执行以下操作:

  • 执行unix命令(pmset -g ps)每隔5秒检查一次该脚本的输出,然后如果该命令的输出低于40%(输出示例为:'来自'AC Power的当前绘图“ -iBox 100%;正在充电'),然后运行unix shell脚本......

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

编辑,对于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

原创,适用于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

答案 1 :(得分:0)

这样的事情会起作用

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