Bash Script To Listen For Shell Command Output

2019-08-10 06:07发布

问题:

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.

回答1:

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


回答2:

Something like this would work

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


标签: macos bash shell