shell脚本:Syntax error: Bad for loop variable错误解决方法

Linux Mint中写了一个简单的shell脚本,利用for..do..done结构计算1+2+3......+100的值,结果执行"sh -n xxx.sh"检测语法时总是报错,但在PC机上可正常运行;
脚本:
[html]  view plain  copy
  1. #!/bin/bash  
  2. #information  
  3.    
  4. PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin  
  5. export PATH  
  6.    
  7. read -p "Please input a num " num  
  8. sum=0  
  9. for ((a=0; a<=$num; a++))  
  10. do   
  11. sum=$(($sum + $a))  
  12. done  
  13. echo "the sum is ==> $sum"  
  14. exit 0  
错误如下:
[html]  view plain  copy
  1. Syntax error: Bad for loop variable  
 分析:
从 ubuntu 6.10 开始,ubuntu 就将先前默认的bash shell 更换成了dash shell;其表现为 /bin/sh 链接倒了/bin/dash而不是传统的/bin/bash。
[html]  view plain  copy
  1. allen@allen-lql ~/workspace/script $ ls -l /bin/sh  
  2. lrwxrwxrwx 1 root root 4 Aug 12 14:29 /bin/sh -> dash  
所以在使用sh执行检测的时候实际使用的是dash,而dash不支持这种C语言格式的for循环写法。

解决办法:
1、将默认shell更改为bash。(bash支持C语言格式的for循环)
[html]  view plain  copy
  1. sudo dpkg-reconfigure dash  

在选择项中选No

2、直接使用bash检测:

[html]  view plain  copy
  1. bash -n xxx.sh  

3、为了确保shell脚本的可移植性,直接更改shell脚本,使用shell支持的for循环格式:

[html]  view plain  copy
  1. for a in `seq $num`  

猜你喜欢

转载自blog.csdn.net/yan3013216087/article/details/78899336