Tony Haynes
Tony Haynes

Reputation: 69

bash not equal operator not working

I've been writing a bash script and I cannot figure out why the != operator is not working.

#/bin/bash
vips=()
vips+=("        Ltm::HTTP Profile: Default_HTTP_Profile")
vips+=("        Ltm::Virtual Address: 10.206.16.76")
for i in "${vips[@]}";
do
    if [[ $i != *"TCP Profile"* ]] || [[ $i != *"OneConnect"* ]] || [[ $i != *"HTTP Profile"* ]]; then
        echo "test"
    fi
done
for i in "${vips[@]}";
do
    echo "$i"
done

The result from this is

    test
    test
        Ltm::HTTP Profile: Default_HTTP_Profile
        Ltm::Virtual Address: 10.206.16.76

As you can see the 2nd array element should no match the if logic.

Upvotes: 1

Views: 4929

Answers (2)

Tony Haynes
Tony Haynes

Reputation: 69

I revised my logic as follows and it works. Thanks for the help.

if [[ $i == *"TCP Profile"* ]] || [[ $i == *"OneConnect"* ]] || [[ $i == *"HTTP Profile"* ]]; then
    :   
else        
    echo "test"
fi

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295472

Let's trace how this executes:

i="        Ltm::HTTP Profile: Default_HTTP_Profile"
if [[ $i != *"TCP Profile"* ]] || [[ $i != *"OneConnect"* ]] || [[ $i != *"HTTP Profile"* ]]; then

First, it runs [[ $i != *"TCP Profile"* ]]. This test returns true, because the string doesn't contain TCP Profile. Thus, the if is true as a whole, and it doesn't need to run any other tests.


What you presumably want, however, is the following:

case $i in
   *"TCP Profile"*|*"OneConnect"*|*"HTTP Profile"*) : ;; # do nothing
   *) echo "test" ;;
esac

...or, alternatively:

if ! [[ $i = *"TCP Profile"* || $i = *"OneConnect"* || $i = *"HTTP Profile"* ]]; then
  echo "test"
fi

Upvotes: 1

Related Questions