Shell 函数的使用示例

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

function online(){
  if ping -c 1 $1 &> /dev/null
  then
    echo "$1 is online"
  else
    echo "$1 is not online"
  fi
}
  online 192.168.111.$1

[root@localhost 20220824]# bash func_online.sh 100
192.168.111.100 is not online

[root@localhost 20220824]# bash func_online.sh 134
192.168.111.134 is online

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

user(){
  if id $1 &>/dev/null
  then
    echo "`grep ^$1 /etc/passwd | cut -d: -f3,7`"
    return 0
  else
    echo "$1 is not exist"
    return 1
  fi
}

read -p "please input username:"  username
until [ "$username" = "quit" -o "$username" = "exit" -o "$username" = "q" ]
do
  user $username
  if [ $? -eq 0 ];then
    read -p "please input username again:" username
  else
    read -p "$username is not exit,please input other username:" username
  fi
done

[root@localhost 20220824]# bash func_users.sh 
please input username:redhat
1000:/bin/bash
please input username again:xzl
1001:/bin/bash
please input username:jkl
jkl is not exist
jkl is not exit,please input other username:q

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

func_file1.sh:

test1 (){
  echo "i am func_lib"
}

func_file2.sh:

. func_file1.sh
test1

结果:

[root@localhost 20220824]# bash func_file2.sh 
i am func_lib

4.利用递归求n的阶乘

fact (){
  num=$1
  if [ $num -eq 1 ]
  then
    echo "1"
  else
    data=$[$num*$(fact $((num-1)))]
    echo $data
  fi
}
read -p "please input number:" num
fact $num

[root@localhost 20220824]# bash factorial.sh 
please input number:1
1
[root@localhost 20220824]# bash factorial.sh 5
please input number:5
120

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值