2

I am having trouble comparing two strings. Even though they are identical when printed, my if statement returns false.

#!/bin/bash

string1="HDMI"
string2="PC Speaker"

hash=$(pacmd list-sinks | grep active)
echo $hash
trigger="active port: <analog-output-speaker>"
echo $trigger

if [ "$hash" == "$trigger" ]; then
   pacmd set-card-profile 0 output:hdmi-stereo+input:analog-stereo  
   echo $string1
else
   pacmd set-card-profile 0 output:analog-stereo+input:analog-stereo    
   echo $string2
fi

It produces the following output:

active port: <analog-output-speaker>
active port: <analog-output-speaker>
Welcome to PulseAudio! Use "help" for usage information.
>>> >>> PC Speaker

3 Answers 3

3

Always quote variables

you say echo $hash but that strips leading and trailing whitespace and condenses all internal spaces. it does not show the content of the variable $hash

say instead echo "<$hash>" and you will see the leading whitespace.

It looks like pulse audio is using a tab before the word active. So put a tab at the start of the value in trigger and it will work.

1

If you add set -vx under #!/bin/bash and then run your script you will see:

[[ active port: <analog-output-speaker> == active port: <analog-output-speaker> ]]

And you can see the strings are not the same because first string has some spaces.

for removing whole string's spaces you can use: trim -d '[[:space:]]

for removing leading string's spaces you can use: sed -e 's/^[[:space:]]*//'

for removing trailing string's spaces you can use: sed -e 's/[[:space:]]*$//'

0

Non-printables troubling you.

Try this:

$ hash="   active port: <analog-output-speaker>%%%%%"   
$ echo $hash
active port: <analog-output-speaker>%%%%%
$ echo "<$hash>"
<   active port: <analog-output-speaker>%%%%%>
$ if [[ "$hash" =~ "active port" ]]; then echo matched; else echo no match; fi
matched
$ if [[ "$hash" =~ "non active port" ]]; then echo matched; else echo no match; fi
no match

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.