OR operator in bash scripting

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.


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.

Tags:

Bash