开发者

Bash if statement syntax error [duplicate]

This question already has answers here: How do I compare two string variables in an 'if' statement in Bash? [duplicate] 开发者_如何学JAVA (12 answers) Closed 7 years ago.

I'm at a loss as to why this is giving a syntax error. Any thoughts?

#!/bin/bash

if [ `date +%H` -lt 11 ] ; then exit 0;
fi

if [ `date +%H` -gt 14 ] ; then
  if[ `date +%H` -lt 20 ] ; then  # <--- this line is the culprit, it seems
    exit 0;
  fi
fi

When run, I get:

./get.sh: line 7: syntax error near unexpected token `then'
./get.sh: line 7: `  if[ `date +%H` -lt 20 ] ; then '


The reason that this is a syntax error is that [ isn't part of the shell syntax; it's actually a command. Originally it was just a symlink to the test command. It still is, but it's also a built-in command in bash and other Bourne-derived shells.

if is a shell keyword, but the shell sees if[, not if. Because it didn't see an if, it doesn't know what to do when it sees then. (Actually, it knows exactly what to do: print a syntax error message.)

...

A bit of experimentation shows that it's not quite as simple as I thought it was. I tried creating a command called if[ and putting it in a directory in my $PATH. When I type just if[ at the prompt, the shell asks for more input. I actually don't know what it's looking for, but apparently the [ character is specially treated by the shell. The shell just doesn't split if[ into the if keyword and the [ command (as you might reasonably expect based on how other languages work). (If I really wanted to execute that command, I could type \if[ or "if[" -- or give it a sane name in the first place.

In any case, that last part probably doesn't matter; adding a space character will fix the problem.


Add space before [

if [ `date +%H` -lt 20 ]


if[ `date +%H` -lt 20 ] ;

you need to place a space after if

if [ `date +%H` -lt 20 ] ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜