我正在试图做一个脚本来检查CA的权力状态
这是我的代码:
#!/bin/bash a=$(acpitool -a) echo "$a" if $a -eq "AC adapter : online" then echo "ONLINE" else echo "OFFLINE" fi
它不工作; variables$a
ia不能与string“AC adapter:online”进行比较。 如何将命令acpitool -a
的输出转换为string?
这是发生了什么事情:
AC adapter : online ./acpower.sh: linha 7: AC: comando não encontrado OFFLINE
问题解决了!
这是新代码,在所有人的帮助下,谢谢。
#!/bin/bash # set the variable a=$(acpitool -a) # remove white spaces a=${a// /} # echo for test echo $a # compare the result if [[ "$a" == 'ACadapter:online' ]] then # then that the imagination is the limit echo "ONLINE" else # else if you have no imagination you're lost echo "OFFLINE" fi
此代码可能在服务器上使用,以提醒电源是否发生故障!
shell(或test
命令)使用=
表示字符串相等, -eq
表示数字相等。 某些版本的shell支持==
作为=
(但是=
由POSIX test
命令定义)的同义词。 相比之下,Perl将==
用于数字相等, eq
用于字符串相等。
您还需要使用其中一个测试命令:
if [ "$a" = "AC adapter : online" ] then echo "ONLINE" else echo "OFFLINE" fi
要么:
if [[ "$a" = "AC adapter : online" ]] then echo "ONLINE" else echo "OFFLINE" fi
用[[
运营商,你可以放弃引号"$a"
。
当你写道:
if $a -eq "AC adapter : online"
shell将其扩展为:
if AC adapter : online -eq "AC adapter : online"
这是执行带有5个参数的命令AC
的请求,并将该命令的退出状态与0进行比较(考虑0 – 成功 – 为真,任何非0为假)。 很明显,你的系统上没有一个叫AC
的命令(这并不是很令人惊讶)。
这意味着你可以写:
if grep -q -e 'some.complex*pattern' $files then echo The pattern was found in some of the files else echo The pattern was not found in any of the files fi
如果要测试字符串,则必须使用test
命令或[[ ... ]]
运算符。 除了命令名是[
,最后一个参数必须是]
之外, test
命令与[
命令相同。
将比较放在方括号中,并在$a
周围添加双引号:
if [ "$a" == "AC adapter : online" ]; then ...
如果没有方括号, bash
尝试执行表达式并计算返回值。
将命令替换放在双引号中也是一个好主意:
a="$(acpitool -a)"
请试试这个 –
#!/bin/bash a="$(acpitool -a)" echo "$a" if [ "$a" == 'AC adapter : online' ] then echo "ONLINE" else echo "OFFLINE" fi
说明: -eq
主要用于整数表达式的等价。 所以,==是要走的路! 并且,使用$ a或$(acpitool -a)中的双引号来防止分词。 即使包含空白分隔符,封闭在双引号内的参数也表示为单个单词。
问题解决了!
这是新代码,在所有人的帮助下,谢谢。
#!/bin/bash # set the variable a=$(acpitool -a) # remove white spaces a=${a// /} # echo for test echo $a # compare the result if [[ "$a" == 'ACadapter:online' ]] then # then that the imagination is the limit echo "ONLINE" else # else if you have no imagination you're lost echo "OFFLINE" fi
此代码可能在服务器上使用,以提醒电源是否发生故障!