1.for语句实例
[root@centos01 ~]# vim /root/users.txt
[root@centos01 ~]# cat /root/users.txt
bob
tom
Alice
[root@centos01 ~]# vim uaddfor.sh
[root@centos01 ~]# cat uaddfor.sh
#!/bin/bash
ulist=$(cat /root/users.txt)
for uname in $ulist
do
useradd $uname
echo “123456” | passwd --stdin $uname &> /dev/null
done
[root@centos01 ~]# chmod +x uaddfor.sh
[root@centos01 ~]# ./uaddfor.sh
[root@centos01 ~]# tail -3 /etc/passwd
bob❌1002:1002::/home/bob:/bin/bash
tom❌1003:1003::/home/tom:/bin/bash
alice❌1004:1004::/home/alice:/bin/bash
[root@centos01 ~]# vim udelfor.sh
[root@centos01 ~]# cat udelfor.sh
#!/bin/bash
ulist=$(cat /root/users.txt)
for uname in $ulist
do
userdel -r KaTeX parse error: Expected 'EOF', got '&' at position 7: ulist &̲> /dev/null don…(cat /root/ipadds.txt)
for ip in $hlist
do
ping -c 3 -i 0.2 -W 3 $ip &> /dev/null
if [ $? -eq 0 ]
then
echo “Host $ip is up.”
else
echo “Host $ip is down.”
fi
done
[root@centos01 ~]# chmod +x chkhosts.sh
[root@centos01 ~]# ./chkhosts.sh
Host 172.16.16.1 is down.
Host 172.16.16.22 is down.
Host 172.16.16.220 is down.
Host 192.168.100.10 is up.
4.
[root@centos01 ~]# vim uaddwhile.sh
[root@centos01 ~]# cat uaddwhile.sh
#!/bin/bash
PREFIX=“stu”
i=1
while [ $i -le 20 ]
do
useradd
P
R
E
F
I
X
{PREFIX}
PREFIXi
echo “123456” | passwd --stdin
P
R
E
F
I
X
{PREFIX}
PREFIXI &> /dev/null
let i++
done
[root@centos01 ~]# chmod +x uaddwhile.sh
[root@centos01 ~]# ./uaddwhile.sh
[root@centos01 ~]# grep “stu” /etc/passwd | tail -3
[root@centos01 ~]# vim udelwhile.sh
[root@centos01 ~]# cat udelwhile.sh
#!/bin/bash
PREFIX=“stu”
i=1
while [ $i -le 20 ]
do
userdel -r
P
R
E
F
I
X
{PREFIX}
PREFIXi
let i++
done
[root@centos01 ~]# chmod +x udelwhile.sh
[root@centos01 ~]# ./udelwhile.sh
[root@centos01 ~]# id stu20
id: stu20: no such user
[root@centos01 ~]# vim pricegame.sh
[root@centos01 ~]# cat pricegame.sh
#!/bin/bash
PRICE=$(expr $RANDOM % 1000)
TIMES=0
echo “商品实际价格范围为0-999,猜猜看是多少?”
while true
do
read -p “请输入你猜测的价格数目:” INT
let TIMES++
if [ $INT -eq $PRICE ] ; then
echo “恭喜你答对了,实际价格是 $PRICE”
echo “你总共猜测了 $TIMES 次”
exit 0
elif [ $INT -gt KaTeX parse error: Expected 'EOF', got '#' at position 71: …oot@centos01 ~]#̲ chmod +x price…KEY" in
[a-z] | [A-Z])
echo “您输入的是 字母。”
;;
[0-9])
echo “您输入的是 数字.”
;;
*)
echo “您输入的是 空格、功能键或其他控制字符.”
esac
[root@centos01 ~]# chmod +x hitkey.sh
[root@centos01 ~]# ./hitkey.sh
请输入一个字符,并按Enter键确认:l
您输入的是 字母。
8.
[root@centos01 ~]# vim myprog
[root@centos01 ~]# cat myprog
#!/bin/bash
case “$1” in
start)
echo -n “正在启动sleep服务…”
if sleep 7200 &
then
echo “OK”
fi
;;
stop)
echo -n “正在停止sleep服务…”
pkill “sleep” &> /dev/null
echo “OK”
;;
status)
if pgrep “sleep” &> /dev/null ; then
echo “sleep服务已经启动.”
else
echo “sleep服务已经停止.”
fi
;;
restart)
$0 stop
$1 start
;;
*)
echo “用法: $0 {start|stop|status|restart}”
esac
[root@centos01 ~]# chmod +x myprog
[root@centos01 ~]# ./myprog status
sleep服务已经启动.