Tristan Šneider
Tristan Šneider

Reputation: 91

Bash script string comparison error, can't figure out

I fixed the code below so it works:

#!/bin/bash
out="$(cat /proc/acpi/bbswitch)"
if [[ "$out" == *OFF* ]];
then
    tee /proc/acpi/bbswitch <<<ON
    echo "Nvidia card activated."
else
    tee /proc/acpi/bbswitch <<<OFF
    echo "Nvidia card disabled."
fi

This is made for activating or disabling my optimus card. I get an error on line 4:

./.bb: line 4: [0000:01:00.0 OFF: command not found
OFF
Nvidia card disabled.

I can read from it that it tries to execute the $out variable. Why?

Upvotes: 1

Views: 557

Answers (1)

sampson-chen
sampson-chen

Reputation: 47267

You need to ensure that there is at least 1 space between the brackets [ / ] and the actual variables; i.e.: change your code from

if ["$out" == "$is"];

to:

if [ "$out" == "$is" ];

And it should work.

The reason is that [ is actually the "test" command in bash. Try on your prompt:

which [

and you should see something like:

/usr/bin/[

Also, man [ to read more about syntax

(Note, since arguments are delimited by spaces, there needs to be a space between your 2nd variable and ] as well. Test uses ] as the terminating sentinel)

Upvotes: 4

Related Questions