shell语言练习5

本文展示了四个Shell脚本实例,包括使用ping命令检测IP列表中的在线主机,检查用户是否存在并获取其shell和UID,从外部脚本调用函数,以及使用递归计算整数的阶乘。这些脚本涵盖了基本的系统管理和脚本编程技巧。
摘要由CSDN通过智能技术生成

目录

1.online写一个脚本,判定给定的IP列表中的主机哪些在线

2.函数能够接受一个参数,参数为用户名;判断一个用户是否存在如果存在,就返回此用户的shell和UID;并返回正常状态值;如果不存在,就说此用户不存在;并返回错误状态值;

3.函数库文件:在一个脚本中调用另一个脚本中的函数

4.利用递归求n的阶乘


1.online写一个脚本,判定给定的IP列表中的主机哪些在线

[root@server shell]# vim func_ping.sh

function func(){

  ping -c 3 -i 0.5 -W 1 $1 &> /dev/null

  if test $? -eq 0

  then

    echo "$1 is up"

  else

    echo "$1 is down"

  fi

}

read -t 10 -p "input a ip address(1.1.1.1 or 1.1.1.0)" ip_addr

ip_num=${ip_addr##*.}

ip_net=${ip_addr%.*}.

if [ $ip_num -eq 0 ]

then

  for i in {0..254}

  do

    func "$ip_net$i"

  done

else

  func "$ip_addr"

fi

2.函数能够接受一个参数,参数为用户名;判断一个用户是否存在如果存在,就返回此用户的shell和UID;并返回正常状态值;如果不存在,就说此用户不存在;并返回错误状态值;

[root@server shell]# vim check_username.sh

function checkusername (){

  count=`cat /etc/passwd | grep -w $1 |wc -l`

  if [ $count -gt 0 ]

  then

    echo "the user is exist"

    all=`cat /etc/passwd |grep $1`

    shell=${all##*:}

    uid=`echo $all|cut -d ":" -f 3 `

    echo "the shell is $shell"

    echo "the uid is $uid"

  else

    echo "the user is not exist"

  fi

}

read -p "input username:" username

checkusername $username

3.函数库文件:在一个脚本中调用另一个脚本中的函数

[root@server shell]# vim functions

function func1(){

        echo "$0"

        echo $1

        echo $*

}

[root@server shell]# vim call_function.sh

. /shell/functions

func1 $@

[root@server shell]# bash call_function.sh 123 234 345

call_function.sh

123

123 234 345

4.利用递归求n的阶乘

[root@server shell]# bash factorial.sh

function factorial(){

  data=$1

  if [ $1 -eq 0 ]

  then

    echo 1

  else

    echo $[data*`factorial $[data-1]`]

  fi

}

read -t 10 -p "input a number:" num

factorial $num

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值