#!/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/bashsum=${1:?'Error,please enter the total number of students!!!! eg:./add-user.sh 100'}groupadd studentfor((i=1;i<=$sum;i++))doif [ $i -ge 0 ] && [ $i -le 9 ];theni="00"$i
i=$((10#$i))
elif [ $i -gt 9 ] && [ $i -le 99 ];theni="0"$i
i=$((10#$i))
elif [ $i -gt 99 ] && [ $i -le 999 ];theni=$ielseecho "Error,please check the total number of students(0<=number<1000)!!!!"exit 0fiusername="04113$i"useradd -g student $usernameecho "$username:$username"| chpasswdecho "$username new finished"done这样就正确了针对本脚本要实现的功能,可以改进如下:修改for循环为for i in `seq -w $sum`另外:可能会用到的一些for循环格式为:1.罗列式:for i in 1 2 3 4 5 ...N2.使用rang的方式for i in {01..100}注意:我在实践过程中发现在此处的结尾标识好像不能为变量,否则替换不成功。3.使用range+step的方式:for i in {01..100..2}4.使用seqfor i in `seq 100`5.C语言式的方式for ((exp1;exp2;exp3))