练习1 1, 设定变量FILE的值为/etc/passwd 2 ,依次向/etc/passwd 中的每个用户问好,并显示对方的shell,形如:Hello,root.your shell:/bin/bash 3,统计一共有多少用户 [root@localhost mscripts]# cat lx14.sh #!/bin/bash FILE=/etc/passwd LINES=wc -l /etc/passwd | cut -d" " -f1
for I in seq 1 $LINES
; do echo "Hello,head -n $I /$FILE |tail -1 |cut -d: -f1
.your shell is head -n $I /$FILE | tail -1 |cut -d: -f7
" done echo "total $LINES users." 练习2 添加10个用户user1到user10,密码同用户名;但要求只有用户不存在的情况下才能添加 [root@localhost mscripts]# cat lx15.sh #!/bin/bash for I in seq 1 10
; do if ! id user$I &> /dev/null; then useradd user$I && echo "user$I" | passwd --stdin user$I &> /dev/null echo "user$I have finshed." fi done 扩展: 接受一个参数; add 添加用户user1...user10 del 删除用户user1...user10 其他 退出 [root@localhost mscripts]# cat lx16.sh #!/bin/bash for I in seq 1 10
; do if [ $1 = add ]; then if id user$I &> /dev/null
; then echo "user$I exist." else useradd user$I echo "user$I" | passwd --stdin user$I &> /dev/null echo "user$I have been fished." fi elif [ $1 = del ]; then userdel -r user$I > /dev/null echo "user$I have been deleted." else echo "quit..." exit 9 fi done
练习 3 写一个脚本,分别显示当前系统上所有默认shell为bash的用户和默认shell为/sbin/nologin的用户,并统计各类shell下的用户总数;显示结果形如:BASH,3USERS,they are: root,redhat,gentoo NOLOGIN,2 users,they are : bin,ftp [root@localhost mscripts]# cat lx17.sh #!/bin/bash NUMBASH=grep "bash$" /etc/passwd | wc -l
NULOGIN=grep "nologin$" /etc/passwd | wc -l
BASHUSERS=grep "bash$" /etc/passwd | cut -d: -f1
LOGINUSERS=grep "nologin$" /etc/passwd | cut -d: -f1
BASHUSERS=echo $BASHUSERS | sed 's@[[:space:]]@,@g'
LOGINUSERS=echo $LOGINUSERS | sed 's@[[:space:]]@,@g'
echo "BASH,$NUMBASH users,they are:" echo "$BASHUSERS" echo "NOLOGIN,$NULOGIN users,they are:" echo "$LOGINUSERS"
练习 4 写一个脚本计算100以内所有奇数的和和所有偶数的和; [root@localhost mscripts]# cat lx18.sh #!/bin/bash declare -i ODD=0 declare -i EVEN=0 for I in seq 1 100
; do if [ echo "$I%2" | bc
-eq 0 ]; then EVEN+=$I else ODD+=$I fi done echo -e "ODD:$ODD.\nEVEN:$EVEN."
练习5 写一个脚本计算100以内能被3整除的所有整数的和; [root@localhost mscripts]# cat lx19.sh #!/bin/bash declare -i WE=0 for I in seq 1 100
; do if [ echo $I%3 | bc
-eq 0 ]; then WE=$[$I+$WE] fi done echo "$WE"