Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an output to string

I'm trying do to a script to check the CA power status

this is my code:

#!/bin/bash

a=$(acpitool -a)

echo "$a"

if $a -eq "AC adapter : online"
then
echo "ONLINE"
else
echo "OFFLINE"
fi

It's not working; the variable $a ia not compare with the the string "AC adapter : online". How to convert the output of command acpitool -a to a string?

This is what happens:

AC adapter     : online 
./acpower.sh: linha 7: AC: comando não encontrado
OFFLINE

Problem solved!

This is the new code, whith the help of all of you, thanks.

#!/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

This code may be use on a server, to alert if the power fails!

like image 955
Hedron Dantas Avatar asked Jul 27 '13 17:07

Hedron Dantas


2 Answers

How to fix the problem

The shell (or the test command) uses = for string equality and -eq for numeric equality. Some versions of the shell support == as a synonym for = (but = is defined by the POSIX test command). By contrast, Perl uses == for numeric equality and eq for string equality.

You also need to use one of the test commands:

if [ "$a" = "AC adapter : online" ]
then echo "ONLINE"
else echo "OFFLINE"
fi

Or:

if [[ "$a" = "AC adapter : online" ]]
then echo "ONLINE"
else echo "OFFLINE"
fi

With the [[ operator, you could drop the quotes around "$a".

Why you got the error message

When you wrote:

if $a -eq "AC adapter : online"

the shell expanded it to:

if AC adapter : online -eq "AC adapter : online"

which is a request to execute the command AC with the 5 arguments shown, and compare the exit status of the command with 0 (considering 0 — success — as true and anything non-zero as false). Clearly, you don't have a command called AC on your system (which is not very surprising).

This means you can write:

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

If you want to test strings, you have to use the test command or the [[ ... ]] operator. The test command is the same as the [ command except that when the command name is [, the last argument must be ].

like image 153
Jonathan Leffler Avatar answered Sep 28 '22 07:09

Jonathan Leffler


Put the comparision in square brackets and add double quotes around the $a:

if [ "$a" == "AC adapter : online" ]; then
  ...

Without the square brackets bash tries to execute the expression and evaluate the return value.

It may also be a good idea to put the command substitution in double quotes:

a="$(acpitool -a)"
like image 42
Ansgar Wiechers Avatar answered Sep 28 '22 05:09

Ansgar Wiechers