分页: 1 / 1
关于shell script中使用for的问题
发表于 : 2012-04-02 18:48
由 fengzhiyoulan
我在ubuntu中练习for循环时,用
read -p "nihao" num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i))
done
echo $s
怎么老是报错说:Bad for loop variable。请各位大哥帮下忙。
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 19:09
由 枫叶饭团
代码: 全选
[maplebeats@maplebeats bash]$ cat test
#!/bin/bash
read -p "nihao" num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i))
done
echo $s
[maplebeats@maplebeats bash]$ sh test
nihao2
3
[maplebeats@maplebeats bash]$ sh test
nihao4436
9841266
[maplebeats@maplebeats bash]$
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 20:39
由 fengzhiyoulan
枫叶饭团 写了:代码: 全选
[maplebeats@maplebeats bash]$ cat test
#!/bin/bash
read -p "nihao" num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i))
done
echo $s
[maplebeats@maplebeats bash]$ sh test
nihao2
3
[maplebeats@maplebeats bash]$ sh test
nihao4436
9841266
[maplebeats@maplebeats bash]$
我前面也是那么写的,不行啊。
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 20:53
由 fengzhiyoulan
这是截图
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 21:07
由 fengzhiyoulan
找到原因了,是ubuntu里的bash在捣鬼,ubuntu里用dash代替了原始的bash,需要sudo dpkg reconfigure dash选no就可以了。
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 21:52
由 aerofox
既然用的是 bash 的语法,就明确指定用 bash 解释,第一行用
题外话:
在 (( )) 内部,变量的引用不需要加 $,加了也没问题。
Re: 关于shell script中使用for的问题
发表于 : 2012-04-02 22:22
由 fengzhiyoulan
aerofox 写了:既然用的是 bash 的语法,就明确指定用 bash 解释,第一行用
题外话:
在 (( )) 内部,变量的引用不需要加 $,加了也没问题。
谢谢,非常感谢两位大哥