LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1255|回复: 10

为什么我写的这个代码老出错?请帮忙看看。谢谢

[复制链接]
发表于 2004-6-2 20:44:37 | 显示全部楼层 |阅读模式
很简单,但是老提示我语法错误。
代码如下,存成test1
#!/bin/bash
a=300
b=333
if[$a<$b]
then
         echo $a
fi
exit 0
提示如下:
jason@nbfan:~$ bash test1
test1: line 4: if[300<333]: command not found
test1: line 5: syntax error near unexpected token `then'
test1: line 5: `then'
jason@nbfan:~$
发表于 2004-6-2 21:31:47 | 显示全部楼层
I guess you want to compare two NUMBER rather than two string. So you should use -lt for less than instead of '>'.
Your code may look like that
a=300
b=333
if [ $a -lt $b ]
then
echo $a
fi
Hope it will help.
 楼主| 发表于 2004-6-2 21:34:44 | 显示全部楼层
#!/bin/bash
a=100
b=200
echo $a $b

if[$a -lt $b]
then
echo $a
fi
exit 0
也不行阿。下面是错误信息
jason@nbfan:~$ bash test1
100 200
test1: line 6: if[100 -lt 200]: command not found
test1: line 7: syntax error near unexpected token `then'
test1: line 7: `then'
jason@nbfan:~$
发表于 2004-6-2 21:46:40 | 显示全部楼层
exit 0是大可不必的,因为正常退出的返回状态就是0。
[php]
#!/bin/bash
a=100
b=200
echo $a $b

if[ $a -lt $b ];then
        #注意,中括号(test的别名)的前后有空格
        #其后的分号也是必要的
        echo $a
fi
[/php]

ps:请多参阅bash的语法基础知识,这是入门必备的,正如你去一个异国,必须掌握那个国家的语言一样
发表于 2004-6-2 22:20:11 | 显示全部楼层
if   [    $a    -lt      $b    ]
分号就不必用了,空格才是必需的。
发表于 2004-6-2 22:22:48 | 显示全部楼层
最初由 neoli 发表
if   [    $a    -lt      $b    ]
分号就不必用了,空格才是必需的。

ps:当然,如果标新立异地来编程,亦无不可。
欲自己的作品保持严谨性,就得从小程序做起,养成良好的编程风格。
 楼主| 发表于 2004-6-2 22:29:36 | 显示全部楼层
刚才在irc里yancy帮我解决了。
各位来打,别一上来就说我不参考就基本语法,我照着学的,是教程没写。
http://263.aka.org.cn/Lectures/002/Lecture-2.1.2/bash-syntax.html
发表于 2004-6-2 23:55:55 | 显示全部楼层
[...]中各项要用空格分开,这是shell的规则~
发表于 2004-6-3 12:06:23 | 显示全部楼层
最初由 neoli 发表
if   [    $a    -lt      $b    ]
分号就不必用了,空格才是必需的。
写个不用分号的 if 给大家看看 :thank
发表于 2004-6-4 23:36:54 | 显示全部楼层

if 和then在同一行要分号的,不在同一行就不用了

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表