Bash Script To Listen For Shell Command Output

2019-08-10 05:17发布

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.

标签: macos bash shell
2条回答
神经病院院长
2楼-- · 2019-08-10 05:57

Something like this would work

pmset -g ps | perl -pe 'if(/%.*Ibox ([0-9]+)%; ch.*$/ and $1 < 40){system "nameofshellscript"}'
查看更多
该账号已被封号
3楼-- · 2019-08-10 06:03

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
查看更多
登录 后发表回答