Linux Mint中写了一个简单的shell脚本,利用for..do..done结构计算1+2+3......+100的值,结果执行"sh -n xxx.sh"检测语法时总是报错,但在PC机上可正常运行;
脚本:
#!/bin/bash
#information
 
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
 
read -p "Please input a num " num
sum=0
for ((a=0; a<=$num; a++))
do 
sum=$(($sum + $a))
done
echo "the sum is ==> $sum"
exit 0
错误如下:
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
所以在使用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`


GitHub 加速计划 / li / linux-dash
9
1
下载
A beautiful web dashboard for Linux
最近提交(Master分支:7 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐