SHELL脚本常见的错误

                                                                             demo.1

执行shell脚本前需要两步:

第一步:修改文件的权限chmod + x  1.sh

第二步运行./1.sh

1、常见的语法错误、代码如下:

#!/bin/bash
n=1
while [[ $n -le 5 ]];
do
 echo "the number is $n"
 let "n+=1"
done

 

分析:经常会由于没有加入do,会在后面done的位置提示意外的出现的关键字

会产生如下错误:

[root@localhost mayday]# ./2.sh
./2.sh:行6: 未预期的符号 `done' 附近有语法错误
./2.sh:行6: `done'

正确的结果如下:

[root@localhost mayday]# ./2.sh
the number is 1
the number is 2
the number is 3
the number is 4
the number is 5

2、演示if语句中由于缺少空格而导致的错误,代码如下:

不带会产生的错误如下:

[root@localhost mayday]# ./3.sh

./3.sh: 第 7 行:[: 缺少 `]'


./3.sh: 第 7 行:[: 缺少 `]'

正确的代码如下:

#!/bin/bash
while :
do
 #接收用户数据输入
 read x
 #如果用户输入的字符串为exit,则退出程序
 if [ $x == "exit" ];then
    exit 0
 else
   echo "$x"
 fi
done

结果显示如下:

[root@localhost mayday]# ./3.sh
a
a
b
b
exit
[root@localhost mayday]# 

3、SHELL编程常遇见的逻辑错误,代码如下:

#!/bin/bash
#定义变量x
 x=1
#当变量x的值为1时
if [ x == 1 ];then
  echo "x=1"
#当变量x的值为0时
elif [ x == 0 ];then
  echo "x=0"
#当变量为其他的值时
else
  echo "other"
fi

结果:

[root@localhost mayday]# ./4.sh
other

并不是我们所想的那样,出现了逻辑错误 

正确的代码如下:

#!/bin/bash
#定义变量x
 x=1
#当变量x的值为1时
if [ $x == 1 ];then
  echo "x=1"
#当变量x的值为0时
elif [ $x == 0 ];then
  echo "x=0"
#当变量为其他的值时
else
  echo "other"
fi

结果如下:

[root@localhost mayday]# ./4.sh
x=1

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值