1.online写一个脚本,判定给定的IP列表中的主机哪些在线
2.函数能够接受一个参数,参数为用户名;
判断一个用户是否存在
如果存在,就返回此用户的shell和UID;并返回正常状态值;
如果不存在,就说此用户不存在;并返回错误状态值;
3.函数库文件:在一个脚本中调用另一个脚本中的函数
4.利用递归求n的阶乘
1.online写一个脚本,判定给定的IP列表中的主机哪些在线
①:直接使用函数实现(无参数,无返回值)
online(){
for i in {40..45};do
if ping -c 1 192.168.2.$i $>/dev/null
then
echo "192.168.2.$i is up"
else
echo "192.168.2.$i is down"
fi
done
}
online
②使用函数传参(有参数,无返回值)
online() {
if ping -c 1 $1 &>/dev/null
then
echo "$1 is up"
else
echo "$1 is down"
fi
}
for i in {42..50}
do
online 192.168.2.$i #主机ip为192.168.2.43
done
[root@localhost task_8.22]# bash online.sh
192.168.2.42 is down
192.168.2.43 is up
192.168.2.44 is down
192.168.2.45 is down
192.168.2.46 is down
192.168.2.47 is down
192.168.2.48 is down
192.168.2.49 is down
192.168.2.50 is down
2.函数能够接受一个参数,参数为用户名;判断一个用户是否存在
ps:如果存在,就返回此用户的shell和UID;并返回正常状态值;
如果不存在,就说此用户不存在;并返回错误状态值;
user() {
if id $1 &>/dev/null
then
echo "`grep ^$1 /etc/passwd | cut -d: -f3,7`"
return 0
else
echo "$1 does not exist"
return 1
fi
}
read -p "please input username:" username
until [ "$username" = "quit" -o "$username" = "exit" -o "$username" = "q" ]
do
user $username
if [ $? == 0 ];then
read -p "please input again:" username
else
read -p "no $username,please input again:" username
fi
done
[root@localhost task_8.22]# sh judge_uid.sh
please input username:root
0:/bin/bash
please input again:redhat
1000:/bin/bash
please input again:tuerqi
tuerqi does not exist
no tuerqi,please input again:0
please input again:exit
3.函数库文件:在一个脚本中调用另一个脚本中的函数
函数库文件:在一个脚本中调用另一个脚本中的函数
函数库文件定义:创建一个函数库文件的过程非常类似于编写一个Shell脚本。脚本与库文件之间的唯一区别在于函数库文件通常只包括函数,而脚本中则可以既包括函数和变量的定义,又包括可执行的代码。此处所说的可执行代码,是指位于函数外部的代码,当脚本被载入后,这些代码会立即被执行,毋需另外调用。
函数库文件的调用
当库文件定义好之后,用户就可以在程序中载入库文件,并且调用其中的函数。在Shell中,载入库文件的命令为.,即一个圆点,其语法如下:
. filename /source filename
其中,参数filename表示库文件的名称,必须是一个合法的文件名。库文件可以使用相对路径,也可以使用绝对路径。另外,圆点命令和库文件名之间有一个空格。
4.利用递归求n的阶乘
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
[root@localhost task_8.22]# sh recursion_n.sh 1
1
[root@localhost task_8.22]# sh recursion_n.sh 13
6227020800