2

This question already has an answer here:

What is the correct format for if then?
I tried lots of varieties.
Should the format work at the command line when not in a program?

$ if [1==2] then echo "y" fi;
> ;
-bash: syntax error near unexpected token `;'

marked as duplicate by Renan, slm, Anthon, jasonwryan, derobert Sep 30 '13 at 20:32

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.

  • 4
    All 3 keywords (if, then, fi) should start their own separate lines. Or have semicolon in front of them: if [ 1 == 2 ]; then echo "y"; fi. Beside that, spaces around ['s arguments are mandatory. – manatwork Sep 30 '13 at 15:40
  • also see that [1==2] must have space between the [ , ] and the numbers, that is [ 1 -eq 2 ] as bash parser needs it. – mandeep Sep 30 '13 at 16:00
1

Try this one:

if [ 1 == 2 ]; then echo "y" ; fi

And better use -eq, unless you want to compare 1 and 2 as a strings.

Useful link: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

3

The correct form of the bash if construct is

if something; then command; fi

The correct form of what you seem to be attempting do do is

if [ 2 -eq 2 ]; then echo "y"; fi;

Spaces are important in bash.

2

Nobody explained the error yet.

You entered:

if [1==2] then echo "y" fi;
;

The first line was perfectly valid syntax as far as the shell was concerned. It is of the form:

if cmd args

In this case, cmd is derived from the expansion of the [1==2] glob. [1==2] is a globbing pattern that expands to the list of files in the current directory whose name consist of either a 1, = or 2 character.

For instance, if there's a file called 2 in the current directory, that becomes:

if 2 then echo fi;

That is run the 2 command with 4 arguments: 2, then, echo and fi, as the first command in the if part of an if/then/elif/else/fi statement.

The error comes from that second ; on the second line. You would have had the same error message by entering that ; alone on the command line. ; must be used to separate commands, it cannot be used on its own like that.

1

The == operator doesn't exist in Bash. It's either -eq when comparing numbers or = when comparing strings.

if [ 1 -eq 2 ]; then echo 'y'; fi
  • == does exist in bash, it just does string comparison, like =. See here. – terdon Sep 30 '13 at 16:08

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