shell脚本初学者注意点
我是shell脚本初学者,在试着写脚本的时候各种不适应。出现摸不着头脑的错误。现在写一些小经验:
首先shell脚本中不要出现空行,不然终端会提示: command not found
使用sh -x xxx.sh 可以调试脚本,如果脚本中出现\r等莫名其妙的东西,说明你的脚本是在dos下面编写的,比如你在windows下面的文本文档编写的,这样会导致shell脚本警告,甚至出错。
你可以使用vi打开脚本,按esc键,输入:set ff=unix :wq 处理下文件,这样就保存成立unix文档格式。
很多报错都是出现在这个问题上,而且很难发现和修改!!!!
1:
定义变量时, =号的两边不可以留空格. 这里不能添加的原因是 添加了空格一般是用来表示判断的
eg:
gender=femal------------right
gender =femal-----------wrong
gender= femal-----------wrong
2
条件测试语句 [ 符号的两边都要留空格 . //这条真的比较膈应人
eg:
if [ $gender = femal ]; then-------right.
echo "you are femal";
fi
if[ $gender...-----------------------wrong
if [$gender...----------------------wrong.
3
条件测试的内容,如果是字符串比较的话, 比较符号两边要留空格!
eg:
if [ $gender = femal ]; then-------right.
if [ $gender= femal ]; then--------wrong.
if [ $gender=femal ]; then---------wrong.
4
如果if 和 then写在同一行, 那么,注意, then的前面要跟上 ; 号.
如果 then 换行写, 那么也没问题.
eg:
if [ $gender = femal ]; then-------right.
if [ $gender = femal ]
then-------------------------------right.
if [ $gender = femal ] then-------wrong. then前面少了 ; 号.
提示出错信息:
syntax error near unexpected token then 这就话出错还可能是由于第二条 "[" 左右都要有空格造成的
同理,还有很多出错信息 比如
syntax error near unexpected token fi 等都是这样引起的。还有就是不是unix文档格式
5
if 后面一定要跟上 then. 同理
elif 后面一定要跟上 then.
不然提示出错信息:
syntax error near unexpected token else
1)if 语句后面需要跟着then,同时前面要有分号;
2) 空格非常重要,shell 会认为空格前的为一个命令,如果a=3 认为是赋值操作,如果写成a = 3,那么就会认为a为一个命令 this=`ls -l |grep '^-' | wc -l `
3) 操作符之间要用空格分开 ,如 test ! -d $1,其中的!和-d就要用空格分开
空格是命令解析中的重要分隔符