Convert an output to string

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 ].


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)"

Please try this -

    #!/bin/bash
    a="$(acpitool -a)"

    echo "$a"

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

Explanation: -eq is mainly used for equivalence for integer expressions. So, == is the way to go! And, use double quotes across $a or $(acpitool -a) to prevent word splitting. An argument enclosed within double quotes presents itself as a single word, even if it contains whitespace separators.