『练习1』:使命令/mnt/create_users.sh /mnt/userfile可为系统添加用户(/mnt/userfil中写入用户名user1 user2 user3)
<使用test命令+for语句实现>
#!/bin/bash
[ "$USER" != "root" ] && {
echo -e "\033[31mError:Permission Denied !!!\033[0m"
exit 0
}
[ -z "$1" ] && {
echo -e "\033[31mError:Please Input userfile following script !!!\033[0m"
exit 0
}
[ -e "$1" ] || {
echo -e "\033[31mError:$1 is not exit !!!\033[0m"
exit 0
}
for USERNAME in `cat $1`
do
useradd $USERNAME &> /dev/null && {
echo -e "\033[32m$USERNAME is created successfully !!!\033[0m"
}||{
echo -e "\033[31m$USERNAME is already exit !!!\033[0m"
}
done
useradd $USERNAME &> /dev/null
: 将添加用户产生的用户信息放入垃圾桶,不显示出来
对于for USERNAME in 'cat $1'
命令的一点说明下:
该命令使用了for
循环,将cat
命令查看到的文件内容赋给 USERNAME
『练习2』:使命令/mnt/create_users.sh /mnt/userfile /mnt/passwdfile可为系统添加用户,并设置好对应密码(/mnt/passwdfile中写入用户密码user1123 user2456 user3789)
<使用test命令+for语句实现>
#!/bin/bash
[ "$USER" != "root" ] && {
echo -e "\033[31mError:Permission Denied !!!\033[0m"
exit 0
}
[ -z "$1" ] && {
echo -e "\033[31mError:Please Input userfile following script !!!\033[0m"
exit 0
}
[ -z "$2" ] && {
echo -e "\033[31mError:Please Input passwdfile following script !!!\033[0m"
exit 0
}
[ -e "$1" ] || {
echo -e "\033[31mError:$1 is not exit !!!\033[0m"
exit 0
}
[ -e "$2" ] || {
echo -e "\033[31mError:$2 is not exit !!!\033[0m"
exit 0
}
Max_Line=`awk 'BEGIN{n=0}{n++}END{print n}' $1`
for NUM in `seq 1 $Max_Line `
do
USERNAME=`sed -n ${NUM}p $1`
PASSWORD=`sed -n ${NUM}p $2`
useradd $USERNAME &> /dev/null && {
echo $PASSWORD | passwd --stdin $USERNAME &> /dev/null
echo -e "\033[32m$USERNAME is created successfully !!!\033[0m"
}||{
echo -e "\033[31m$USERNAME is already exit !!!\033[0m"
}
done
echo -e "\033[31m输出内容\033[0m"
输出内容显示为红色字体
echo -e "\033[32m输出内容\033[0m"
输出内容显示为绿色字体
-e 激活转译字符
\033~~~\033 固定写法
[0m 关闭属性