105

My whole script is currently this:

#!/bin/sh   
clear;   
blanko="";   
# Dummy-Variablen
variable=Testvariable;   
if [[$variable == $blanko]];
then   
  echo "Nichts da!"   
else   
  echo $variable   
fi

and if I enter

TestSelect.sh

I get

/usr/bin/TestSelect.sh: line 6: [[Testvariable: command not found   
Testvariable

How can I fix this?

codeforester
  • 39,467
  • 16
  • 112
  • 140
EpsilonAlpha
  • 1,153
  • 2
  • 7
  • 4
  • 17
    Tip for the future: [shellcheck](http://www.shellcheck.net) will automatically point out this and other basic issues. – that other guy Nov 01 '13 at 21:09
  • 2
    Another pointer: you only need a statement-terminating `;` if you're putting _multiple_ statements on a single line. – mklement0 Nov 02 '13 at 02:46
  • 2
    You need spaces between `[[` and `$variable` and `$blanko` and `]]` – Marcello Romani Jan 20 '19 at 11:02
  • Other question is about use of [ which is an external utility in Unix but this is different problem – anubhava Aug 03 '22 at 08:16
  • Double check that you don't have a **non breaking space** instead of a regular space. I often typo a nbsp instead of a space and cause this to fail in a hard-to-understand/debug way. – odinho - Velmont Jun 21 '23 at 09:20

4 Answers4

235

This is problem:

if [[$variable == $blanko]];

Spaces are required inside square brackets, use it like this:

[[ "$variable" == "$blanko" ]] && echo "Nichts da!" || echo "$variable"
anubhava
  • 761,203
  • 64
  • 569
  • 643
37

On a related note, spaces are required around [ ] as well:

if [ "$variable" = "$blanko" ]; then
  # more code here
fi

Note that variables do need to be enclosed in double quotes inside [ ] to prevent word splitting and globbing. Double quotes also help when either of the variables being compared is not set - shell will throw a syntax error otherwise.

Look at the following post to understand why we need spaces around [ ]:

Another related post that talks about other syntax elements that need spaces as well:

Finally, this post talks about the difference between [[ ]] and [ ]:


Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

Just use #!/bin/bash on tope of script if you are using bash scripting like: if [[ $partition == "/dev/sda2" ]]; then to compare string and run script with ./scriptname.sh or bash scriptname.sh

ankit
  • 2,591
  • 2
  • 29
  • 54
-1

If your script runs on your local with /bin/bash but not on your container with sh, then consider adding bash to your container by apk add --no-cache bash.

Danny
  • 114
  • 4
  • 9