Comparing strings in bash. [[: not found

I am trying to compare strings in bash. I have already found the answer on how to do this on https://stackoverflow.com/a/3/2208/ . In the script I am trying, I am using the code provided by Adam in the indicated question:

#!/bin/bash string='My string'; if [[ "$string" == *My* ]] then echo "It there!"; fi needle='ys' if [[ "$string" == *"$needle"* ]]; then echo "haystack '$string' contains needle '$needle'" fi 

I also tried the approach from ubuntuforums , which you can find in the 2nd post

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

In both cases, I get an error message:

 [[: not found 

What am I doing wrong?

+79
bash shell string-comparison
Sep 01 '12 at 19:23
source share
6 answers

[[ represents bash -builtin. Your /bin/bash not the actual bash.

+66
Sep 01 '12 at 19:27
source share

How do you use a script? If you are done with

 $ sh myscript 

You must try:

 $ bash myscript 

or, if the script is executable:

 $ ./myscript 

sh and bash are two different shells . Although in the first case you pass your script as an argument to the sh interpreter, in the second case you select the first line in which the interpreter will be used.

+87
Sep 01 '12 at 19:32
source share

This is the first line in the script:

 #!/bin/bash 

or

 #!/bin/sh 

the sh shell generates these error messages, not bash

+54
May 6 '13 at 16:58
source share

I had this problem when installing Heroku Toolbelt

This is how I solved the problem

 $ ls -l /bin/sh lrwxrwxrwx 1 root root 4 ago 15 2012 /bin/sh -> dash 

As you can see, / bin / sh is a reference to a dash (not bash), and [[ - bash is syntactic sugar. So I just replaced the link with / bin / bash. Caution using rm on your system!

 $ sudo rm /bin/sh $ sudo ln -s /bin/bash /bin/sh 
+11
Jul 19 '13 at 18:28
source share

As @Ansgar mentioned, [[ is bagism, i.e. Built-in Bash and inaccessible to other shells. If you want your script to be portable, use [ . Comparison will also require a different syntax: change == to = .

+5
May 30 '16 at 14:55
source share

Set bash instead of sh when running the script. I personally noticed that they are different from ubuntu 12.10:

bash script.sh arg0 ... argn

+3
Dec 13 '14 at 11:46
source share



All Articles