开发者

Bash Script To Listen For Shell Command Output

开发者 https://www.devze.com 2023-02-14 05:52 出处:网络
Quick qu开发者_运维百科estion. How would I go about having a shell script to do the following:

Quick qu开发者_运维百科estion. 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.


Edit, for Bash 2.05 and later:

#!/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:

#!/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


Something like this would work

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

精彩评论

暂无评论...
验证码 换一张
取 消