Shell脚本中的常见错误
实际上,Shell脚本的编写过程就说不断排错的过程,以下列出了Shell程序设计中常见的错误
常见的语法错误
在进行Shell程序设计的时候,语法错误经常出现在关键字书写错误,引号错误,漏掉空格符以及变量的大小写问题等
示例1:
if 条件语句缺少结尾关键字引起的错误
[root@kittod ~]# cat 1301.sh
#!/bin/bash
if [ 10 -lt 12 ]
then
echo "Yes,10 id less then 12"
[root@kittod ~]# bash 1301.sh
1301.sh: line 6: syntax error: unexpected end of file
示例2:
循环结构语句中缺少关键字引起的错误
for、while、until、case语句中的错误是指实际语句段不正确,也许是漏写或拼错了固定结构中的一个保留字
[root@kittod ~]# cat 1302.sh
#!/bin/bash
n=1
while [ $n -le 5 ]
echo "the number is $n."
let "n+=1"
done
[root@kittod ~]# bash 1302.sh
1302.sh: line 7: syntax error near unexpected token `done'
1302.sh: line 7: `done'
示例3:
成对的符弓有 []、()、{}、""、''、``等,如果它们落单了,也会导致一些错误
[root@kittod ~]# cat 1303.sh
#!/bin/bash
while :
do
read x
if [ $x == "exit"];then
exit 0
else
echo "$x"
fi
done
[root@kittod ~]# bash 1303.sh
3
1303.sh: line 6: [: missing `]'
3
常见的逻辑错误
通常情况下,Shell脚本中的语法错误是非常明显的,并且语法错误一般会导致程序不可执行,但是逻辑错误就比较隐蔽,因为这些错误通常不好引起程序执行失败,但是逻辑错误却会导致程序得到错误的结果。因此,相比于语法错误,逻辑错误调试会更难
示例:
[root@localho