我正在尝试编写一个脚本来监控作为服务器运行的笔记本电脑上的某些电池状态。为了实现这一点,我已经开始编写以下代码:
#! /bin/bash
# A script to monitor battery statuses and send out email notifications
#take care of looping the script
for (( ; ; ))
do
#First, we check to see if the battery is present...
if(cat /proc/acpi/battery/BAT0/state | grep 'present: *' == present: yes)
{
#Code to execute if battery IS present
#No script needed for our application
#you may add scripts to run
}
else
{
#if the battery IS NOT present, run this code
sendemail -f [email protected] -t 214*******@txt.att.net -u NTA TV Alert -m "The battery from the computer is either missing, or removed. Please check ASAP." -s smtp.gmail.com -o tls=yes -xu [email protected] -xp ***********
}
#Second, we check into the current state of the battery
if(cat /proc/acpi/battery/BAT0/state | grep 'charging state: *' == 'charging state: charging')
{
#Code to execute if battery is charging
sendemail -f [email protected] -t 214*******@txt.att.net -u NTA TV Alert -m "The battery from the computer is charging. This MIGHT mean that something just happened" -s smtp.gmail.com -o tls=yes -xu [email protected] -xp ***********
}
#If it isn't charging, is it discharging?
else if(cat /proc/acpi/battery/BAT0/state | grep 'charging state: *' == 'charging state: discharging')
{
#Code to run if the battery is discharging
sendemail -f [email protected] -t 214*******@txt.att.net -u NTA TV Alert -m "The battery from the computer is discharging. This shouldn't be happening. Please check ASAP." -s smtp.gmail.com -o tls=yes -xu [email protected] -xp ***********
}
#If it isn't charging or discharging, is it charged?
else if(cat /proc/acpi/battery/BAT0/state | grep 'charging state: *' == 'charging state: charged')
{
#Code to run if battery is charged
}
done
我很确定其他大部分内容都能正常工作,但我无法尝试,因为它无法运行。每当我尝试运行脚本时,都会出现以下错误:
./BatMon.sh: line 15: syntax error near unexpected token `}'
./BatMon.sh: ` }'
这个错误是不是非常简单,比如忘记了分号?
答案1
这里有几个问题:
首先,这不是在 bash 中编写 if/else 语句的方式。相反,你需要类似这样的代码:
if <condition>
then
<action>
elif <other-condition>
then
<other-action>
else
<another-action>
fi
其次,condition
您在此处检查的将不起作用;该if
语句将检查的返回值condition
。因此,您需要将条件作为命令(或命令管道)返回零或非零退出状态。
因此,尝试以下方法:
if grep 'present:.*yes' /proc/acpi/battery/BAT0/state
then
# code to execute if battery is present
else
# code to execute if battery is not present
fi
BAT0/state
在这种情况下,如果文件与模式匹配,grep 将成功(即返回零退出状态)present:.*yes
。
如果需要进行字符串匹配,需要使用[
带=
运算符的命令:
if [ "$somevar" = 'some-string' ]
then
# code to execute when $somevar equals 'some-string'
fi
有关 bash 中的 -statements 的更多信息if
,请参阅以下帮助if
:
help if
或者,参阅 bash 手册页以获取一般 bash 编程信息:
man bash