【问题标题】:Bash Script To Listen For Shell Command Output用于侦听 Shell 命令输出的 Bash 脚本
【发布时间】:2011-02-27 19:20:06
【问题描述】:

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

  • 执行 unix 命令 (pmset -g ps) 每 5 秒检查一次该脚本的输出,然后如果该命令的输出低于 40%(输出示例为:'Currenty drawing from 'AC Power ' -iBox 100%;充电'),然后让它运行一个 unix shell 脚本......

任何帮助将不胜感激。

【问题讨论】:

    标签: macos bash shell


    【解决方案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
    

    【讨论】:

    • ./listener.sh:第 10 行:需要条件二元运算符 ./listener.sh:第 10 行:=~' ./listener.sh: line 10: [[ $result =~ $pattern ]]' 附近的语法错误有什么想法吗? ?
    • @Elliot:什么版本的 Bash?您使用的是第二行中显示的$pattern 的值还是不同的值?
    • @Dennis:我使用与上面显示的完全相同的东西,但是如果条件为真,则使用echo "execute script" 而不是实际执行脚本以用于测试目的......我使用的是 bash 版本 2.05b .0(1)
    • @Elliot:不幸的是,正则表达式匹配是在 Bash 3.1 中添加的(但只能在 3.2 及更高版本中使用)。我还注意到我的脚本中有一个错误。我会解决这个问题并发布一个适用于 Bash 2.05b 的版本。
    • @Elliot:显然我误解了pmset 的输出内容。将数字从文本中拆分出来的大括号扩展取决于它是一种特定的方式。显然“-iBox”和数字之间有一个标签。请参阅我编辑的答案。我在开头附近添加了一行并将第一个分配的行更改为threshold
    【解决方案2】:

    这样的事情会起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多