bash:value too great for base (error token is "08")错误解决

16074阅读 1评论2012-06-03 jieoulinux
分类:Python/Ruby

今天在邮件列表里有同学在编写shell脚本时产生了错误,提示为:value too great for base (error token is "08"),上网查了后发现是进制相关的问题,代码为:
#!/bin/bash
 sum=${1:?'Error,please enter the total number of students!!!!  eg:./add-user.sh 100'}
 groupadd student
  
 for((i=1;i<=$sum;i++))
 do
          if [ $i -ge 0 ] && [ $i -le 9 ];then
                  i="00"$i
          elif [ $i -gt 9 ] && [ $i -le 99 ];then
                  i="0"$i                                                                                                            
          elif [ $i -gt 99 ] && [ $i -le 999 ];then
                  i=$i
          else 
                  echo "Error,please check the total number of students(0<=number<1000)!!!!"
                  exit 0
          fi
  
          username="04113$i"
          useradd -g student $username
          echo "$username:$username"| chpasswd
          echo "$username new finished"
  done

在给定的参数大于个位大于9的时候就出问题,这是进制识别的问题,本事例中,变量“i”是以“0”开头的,
bash将它识别为八进制了,所以产生了问题,需要将八进制转换为十进制来解决问题,修改后的代码如下:
#!/bin/bash
 sum=${1:?'Error,please enter the total number of students!!!!  eg:./add-user.sh 100'}
 groupadd student
  
 for((i=1;i<=$sum;i++))
 do
          if [ $i -ge 0 ] && [ $i -le 9 ];then
                  i="00"$i
                       i=$((10#$i))
          elif [ $i -gt 9 ] && [ $i -le 99 ];then
                  i="0"$i
                       i=$((10#$i)) 
                                                                                                           
          elif [ $i -gt 99 ] && [ $i -le 999 ];then
                  i=$i
          else 
                  echo "Error,please check the total number of students(0<=number<1000)!!!!"
                  exit 0
          fi
  
          username="04113$i"
          useradd -g student $username
          echo "$username:$username"| chpasswd
          echo "$username new finished"
  done
这样就正确了

针对本脚本要实现的功能,可以改进如下:
修改for循环为for i in `seq -w $sum`


另外:可能会用到的一些for循环格式为:
1.罗列式:
for i in 1 2 3 4 5 ...N
2.使用rang的方式
for i in {01..100}注意:我在实践过程中发现在此处的结尾标识好像不能为变量,否则替换不成功。
3.使用range+step的方式:
for i in {01..100..2}
4.使用seq
for i in `seq 100`
5.C语言式的方式
for ((exp1;exp2;exp3))
上一篇:shell小技巧:输入密码时禁止回显
下一篇:没有了

文章评论