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 `;'
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 `;'
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.
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
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
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[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