2

This code generates a error line 3: [: missing `]'. So why am I getting such error?

#!/bin/bash
read x
if [ $x == "Y" ] || [ $x == "y"]
then
   echo "YES"
else
   echo "NO"
fi

Thanks in advance.

marked as duplicate by cuonglm, choroba, Anthon, chaos, don_crissti Nov 12 '14 at 11:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • FYR it is much simple use case for your example – Costas Nov 12 '14 at 9:51
  • 1
    Just add space between "y" and ]. – jimmij Nov 12 '14 at 9:52
7

you need to add a space between " and ]

$ ./test.sh
Y
YES

$ cat test.sh
#!/bin/bash 
read x
if [ $x == "Y" ] || [ $x == "y" ] 
then
    echo "YES"
else
    echo "NO"
fi

Cheers.

  • Ohh yes.. got it working correctly. Thank you. :) – Rajat Garg Nov 12 '14 at 10:13
2

The opening bracket [ is actually a command (although it is also available as a shell builtin, but that is a different story).

$ which [
/usr/bin/[

The shell runs this command with the options given. In your case, there will be one invocation with the four options $x, ==, Y, and ], and another one with the three options $x, ==, and y]. This is because the shell uses whitespace to separate options from commands, and from another. Quote signs (") are not passed on, but instead used by the shell to "escape" special meanings of certain characters (e.g. when you need to pass whitespace to a command).

At this point, the shell is done with the square brackets (and everything in-between), and it is up to the [ command to do something useful. [ is programmed to expect ] as its last parameter (for obvious reasons; note that when called as test, another name for the same command, ] is not expected). Because of the lacking whitespace, ] is not found, and [ complains.

-1

You have to use double brace and enclose your variables with "":

#!/bin/bash
read x;
if [[ "$x" = "Y" ||  "$x" = "y" ]];  then
   echo "YES"
else
   echo "NO"
fi;

However i prefer to use:

echo $x |tr '[A-Z]' '[a-z]'

It's very better than if-statement.

  • Huh? What about tr? It is supposed to do the same? – Ondra Žižka Aug 30 '18 at 16:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.