String comparison in bash. [[: not found

user1581900 picture user1581900 · Sep 1, 2012 · Viewed 156.9k times · Source

I am trying to compare strings in bash. I already found an answer on how to do it on stackoverflow. In script I am trying, I am using the code submitted by Adam in the mentioned question:

#!/bin/bash
string='My string';

if [[ "$string" == *My* ]]
then
  echo "It's there!";
fi

needle='y s'
if [[ "$string" == *"$needle"* ]]; then
  echo "haystack '$string' contains needle '$needle'"
fi

I also tried approach from ubuntuforums that you can find in 2nd post

if [[ $var =~ regexp ]]; then
  #do something
fi

In both cases I receive error:

[[: not found

What am I doing wrong?

Answer

Akos K picture Akos K · Sep 1, 2012

How you are running your script? If you did with

$ sh myscript

you should try:

$ bash myscript

or, if the script is executable:

$ ./myscript

sh and bash are two different shells. While in the first case you are passing your script as an argument to the sh interpreter, in the second case you decide on the very first line which interpreter will be used.