Shell 编程 until语句-LMLPHP

本篇主要写一些shell脚本until语句的使用。


计算1-50的和

#!/bin/bash
i=0
s=0
until [ $i -eq 51 ];do
let s+=i;let i++
done
echo $s
[root@localhost ~]# vim sum.sh
[root@localhost ~]# chmod +x sum.sh
[root@localhost ~]# ./sum.sh
1275

为指定用户发送在线消息

#!/bin/bash
username=$1
# 判断格式是否正确
if [ $# -lt 1 ] ;then
echo "Usage:`basename $0` <username> [message]"
exit 1
fi
# 判断用户是否存在
if grep "^$username:" /etc/passwd > /dev/null ;then :
else
echo "用户不存在"
exit 1
fi
# 判断用户是否在线,不在则每5s联系一次
until who|grep "$username" > /dev/null ;do
echo "用户不在线"
sleep 5
done
# 发送信息
mes=$*
echo $mes | write $username
[root@localhost ~]# vim message.sh
[root@localhost ~]# chmod +x message.sh
[root@localhost ~]# ./message.sh
Usage:message.sh <username> [message]
[root@localhost ~]# ./message.sh zhangsan hello
用户不存在
[root@localhost ~]# useradd zhangsan && echo "000000" | passwd --stdin zhangsan
Changing password for user zhangsan.
passwd: all authentication tokens updated successfully.
[root@localhost ~]# ./message.sh zhangsan hello
用户不在线
用户不在线
^C
[zhangsan@localhost ~]$
[root@localhost ~]# ./message.sh zhangsan hello
[zhangsan@localhost ~]$
Message from root@localhost on pts/0 at 02:25 ...
zhangsan hello
EOF
04-30 22:26