我在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。请各位大哥帮下忙。
关于shell script中使用for的问题
版面规则
我们都知道新人的确很菜,也喜欢抱怨,并且带有浓厚的Windows习惯,但既然在这里询问,我们就应该有责任帮助他们解决问题,而不是直接泼冷水、简单的否定或发表对解决问题没有任何帮助的帖子。乐于分享,以人为本,这正是Ubuntu的精神所在。
我们都知道新人的确很菜,也喜欢抱怨,并且带有浓厚的Windows习惯,但既然在这里询问,我们就应该有责任帮助他们解决问题,而不是直接泼冷水、简单的否定或发表对解决问题没有任何帮助的帖子。乐于分享,以人为本,这正是Ubuntu的精神所在。
-
- 帖子: 23
- 注册时间: 2011-12-14 19:47
- 枫叶饭团
- 帖子: 14683
- 注册时间: 2010-06-16 1:05
- 系统: Mac OS X
- 来自: Tencent
- 联系:
Re: 关于shell script中使用for的问题
代码: 全选
[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]$
-
- 帖子: 23
- 注册时间: 2011-12-14 19:47
Re: 关于shell script中使用for的问题
我前面也是那么写的,不行啊。枫叶饭团 写了:代码: 全选
[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]$
-
- 帖子: 23
- 注册时间: 2011-12-14 19:47
-
- 帖子: 23
- 注册时间: 2011-12-14 19:47
Re: 关于shell script中使用for的问题
找到原因了,是ubuntu里的bash在捣鬼,ubuntu里用dash代替了原始的bash,需要sudo dpkg reconfigure dash选no就可以了。
-
- 帖子: 1453
- 注册时间: 2008-05-24 8:30
Re: 关于shell script中使用for的问题
既然用的是 bash 的语法,就明确指定用 bash 解释,第一行用
题外话:
在 (( )) 内部,变量的引用不需要加 $,加了也没问题。
代码: 全选
#!/bin/bash
在 (( )) 内部,变量的引用不需要加 $,加了也没问题。
-
- 帖子: 23
- 注册时间: 2011-12-14 19:47
Re: 关于shell script中使用for的问题
谢谢,非常感谢两位大哥aerofox 写了:既然用的是 bash 的语法,就明确指定用 bash 解释,第一行用题外话:代码: 全选
#!/bin/bash
在 (( )) 内部,变量的引用不需要加 $,加了也没问题。