linux – 将输出转换为字符串
我正在尝试使用脚本来检查CA电源状态
这是我的代码: #!/bin/bash a=$(acpitool -a) echo "$a" if $a -eq "AC adapter : online" then echo "ONLINE" else echo "OFFLINE" fi 它不起作用;变量$a ia与字符串“AC adapter:online”无法比较.如何将命令acpitool -a的输出转换为字符串? 这是发生的事情: 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(或测试命令)使用=表示字符串相等,使用-eq表示数字相等.某些版本的shell支持==作为=的同义词(但是=由POSIX 您还需要使用以下测试命令之一: 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" 这是一个执行命令AC的请求,显示5个参数,并将命令的退出状态与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命令与[命令相同,但命令名称为[,最后一个参数必须为]时除外). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |