1, for loop
for 变量名 [ in 取值列表 ]
do
循环体
done
By default, the for loop separates the variable values by spaces. Note that the number of loops for the for loop is fixed.
for val in a b c
do
echo $val
done
Note that the above script will output abc
The following example realizes that for creating multiple users, you need to create a file. The format of each line in the file is: user name password
#!/usr/bin/bash
#判断脚本是否有参数
if [ $# -eq 0 ]; then
echo "usage: `basename $0` file"
exit 1
fi
#希望for处理文件按回车分隔,而不是空格或tab空格
#重新定义分隔符
#IFS内部字段分隔符
IFS=$'\n'
for line in `cat $1`
do
if [ ${#line} -eq 0 ]; then
continue
fi
user=`echo "$line" | awk '{print $1}'`
pass=`echo "$line" | awk '{print $2}'`
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user already exists"
else
useradd $user
echo "$pass" |passwd --stdin $user &>/dev/null
if [ $? -eq 0 ];then
echo "$user is created"
fi
fi
done
2. The while loop
while 条件测试
do
循环体
done
Because for uses a space as a delimiter, while while can directly use a carriage return as a delimiter, when the file needs to be processed, the priority is while instead of for.
#!/usr/bin/bash
#while create user
#会从文件user.txt里面读入一行给user
#当读到文件尾时,read line不会成功
while read line
do
user=`echo "$line" | awk '{print $1}'`
pass=`echo "$line" | awk '{print $2}'`
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user already exists"
else
useradd $user
echo "$pass" |passwd --stdin $user &>/dev/null
if [ $? -eq 0 ];then
echo "$user is created"
fi
fi
done < user.txt