2

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 `;'
Michael Durrant
  • 41,213
  • 69
  • 165
  • 232
  • 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

4 Answers4

4

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.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
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.

guntbert
  • 1,597
  • 1
  • 17
  • 23
terdon
  • 234,489
  • 66
  • 447
  • 667
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

dchirikov
  • 3,818
  • 2
  • 15
  • 18
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
Spack
  • 1,987
  • 1
  • 17
  • 18
  • 1
    `==` does exist in bash, it just does string comparison, like `=`. See [here](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html). – terdon Sep 30 '13 at 16:08