【发布时间】:2011-02-27 19:20:06
【问题描述】:
快速提问。我将如何使用 shell 脚本来执行以下操作:
- 执行 unix 命令 (pmset -g ps) 每 5 秒检查一次该脚本的输出,然后如果该命令的输出低于 40%(输出示例为:'Currenty drawing from 'AC Power ' -iBox 100%;充电'),然后让它运行一个 unix shell 脚本......
任何帮助将不胜感激。
【问题讨论】:
快速提问。我将如何使用 shell 脚本来执行以下操作:
任何帮助将不胜感激。
【问题讨论】:
编辑,适用于 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: line 10: [[ $result =~ $pattern ]]' 附近的语法错误有什么想法吗? ?
$pattern 的值还是不同的值?
echo "execute script" 而不是实际执行脚本以用于测试目的......我使用的是 bash 版本 2.05b .0(1)
pmset 的输出内容。将数字从文本中拆分出来的大括号扩展取决于它是一种特定的方式。显然“-iBox”和数字之间有一个标签。请参阅我编辑的答案。我在开头附近添加了一行并将第一个分配的行更改为threshold。
这样的事情会起作用
pmset -g ps | perl -pe 'if(/%.*Ibox ([0-9]+)%; ch.*$/ and $1 < 40){system "nameofshellscript"}'
【讨论】: