目录
1.online写一个脚本,判定给定的IP列表中的主机哪些在线
2.函数能够接受一个参数,参数为用户名;判断一个用户是否存在
1.online写一个脚本,判定给定的IP列表中的主机哪些在线
[root@localhost test02]# vim online.sh
function online()
{
for i in $@
do
ping -i 0.2 -c 2 -w 1 $i &> /dev/null
if [ $? -eq 0 ]
then
echo "$i online"
fi
done
}
online 192.168.132.{120..140}
运行结果
[root@localhost test02]# bash online.sh
192.168.132.128 online
192.168.132.129 online
2.函数能够接受一个参数,参数为用户名;判断一个用户是否存在
如果存在,就返回此用户的shell和UID;并返回正常状态值;
如果不存在,就说此用户不存在;并返回错误状态值;
[root@localhost test02] vim user_exist.sh
func_user(){
read -p "input a user:" use
id $use &> /dev/null
if [ $? -eq 0 ]
then
echo `cat /etc/passwd|grep ^$use|cut -d ":" -f3,7`
return 0
else
echo "user $use not exist"
return 1
fi
}
func_user
脚本检验:
![](https://img-blog.csdnimg.cn/682485314f684c2a87db354a5ae6dad1.png)
3.函数库文件:在一个脚本中调用另一个脚本中的函数
[root@localhost test02] vim call_function.sh
. user_exist.sh
func_user
source /test02/online.sh
online 192.168.132.{125..130}
脚本检验
![](https://img-blog.csdnimg.cn/fd4bc6e1887d48acb5792135d3131031.png)
4.利用递归求n的阶乘
[root@localhost test02] vim n_factorial.sh
function n_factor()
{
local n=$1
if [ $n -eq 0 ]
#if [ $n -eq 0 ]
then
result=1
else
let m=$n-1
n_factor $m
let "result=$n*$result"
fi
}
n_factor $1
echo $result
脚本检验