将输出转换为字符串

Hed*_*tas 4 linux bash shell ubuntu

我正在尝试使用脚本来检查CA电源状态

这是我的代码:

#!/bin/bash

a=$(acpitool -a)

echo "$a"

if $a -eq "AC adapter : online"
then
echo "ONLINE"
else
echo "OFFLINE"
fi
Run Code Online (Sandbox Code Playgroud)

它不起作用; 变量$aia与字符串"AC adapter:online"无法比较.如何将命令输出转换acpitool -a为字符串?

这是发生的事情:

AC adapter     : online 
./acpower.sh: linha 7: AC: comando não encontrado
OFFLINE
Run Code Online (Sandbox Code Playgroud)

问题解决了!

这是新代码,在大家的帮助下,谢谢.

#!/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
Run Code Online (Sandbox Code Playgroud)

此代码可以在服务器上使用,以在电源出现故障时发出警报!

Jon*_*ler 7

如何解决问题

shell(或test命令)=用于字符串相等和-eq数字相等.某些版本的shell支持==作为=(但=由POSIX test命令定义)的同义词.相比之下,Perl ==用于数字相等和eq字符串相等.

您还需要使用以下测试命令之一:

if [ "$a" = "AC adapter : online" ]
then echo "ONLINE"
else echo "OFFLINE"
fi
Run Code Online (Sandbox Code Playgroud)

要么:

if [[ "$a" = "AC adapter : online" ]]
then echo "ONLINE"
else echo "OFFLINE"
fi
Run Code Online (Sandbox Code Playgroud)

使用[[运营商,您可以删除报价"$a".

为什么你收到错误信息

你写的时候:

if $a -eq "AC adapter : online"
Run Code Online (Sandbox Code Playgroud)

shell将其扩展为:

if AC adapter : online -eq "AC adapter : online"
Run Code Online (Sandbox Code Playgroud)

这是一个请求执行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
Run Code Online (Sandbox Code Playgroud)

如果要测试字符串,则必须使用test命令或[[ ... ]]运算符.该test命令与[命令相同,只是当命令名称为时[,最后一个参数必须为].