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

墨蓝 2023-01-21 10:22 322阅读 0赞

Kali中写了一个简单的shell脚本,利用for..do..done结构计算值,结果执行”sh -n xxx.sh”检测语法时总是报错
脚本:

  1. read x
  2. if [ $x -lt 2 -o $x -gt 10 ]
  3. then
  4. echo "x must in [2,10]"
  5. exit
  6. fi
  7. echo -n @
  8. for((i=1;i<=$x-2;i++))
  9. do
  10. echo -n +
  11. done
  12. echo @
  13. for((i=1;i<=$x-2; i++))
  14. do
  15. echo -n '&'
  16. for((j=1;j<=$x-2;j++))
  17. do
  18. echo -n " "
  19. done
  20. echo "&"
  21. done
  22. echo -n @
  23. for((i=1;i<=$x-2;i++))
  24. do
  25. echo -n +
  26. done
  27. echo @

错误如下:

Syntax error: Bad for loop variable

分析:
从 ubuntu 6.10 开始,ubuntu 就将先前默认的bash shell 更换成了dash shell;其表现为 /bin/sh 链接倒了/bin/dash而不是传统的/bin/bash。

allen@allen-lql ~/workspace/script $ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Aug 12 14:29 /bin/sh -> dash

kali下也是如此

所以在使用sh执行检测的时候实际使用的是dash,而dash不支持这种C语言格式的for循环写法。

解决办法:
1、将默认shell更改为bash。(bash支持C语言格式的for循环)

sudo dpkg-reconfigure dash

在选择项中选No

2、直接使用bash检测:

bash -n xxx.sh

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

for a in `seq $num`

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读