Linux函数

一、概述
函数是一段完成特定功能的代码片段(块),在shell中定义了函数,就可以使代码模块化,便于复用代码。注意函数必须先定义才可以使用。
二、定义函数
1.方法一:
函数名() {
函数要实现的功能代码
}
2.方法二:
function 函数名 {
函数要实现的功能代码
}
三、调用函数
1.函数名 -->函数名调用函数
2.函数名 参数1 参数2 -->函数传参 位置参数
四、示例
1.示例1:初识函数
编写循环脚本,功能菜单
provide these tools:
show disk info(d)
show mem info(m)
show cpu info©
quit(q)

[root@localhost ~]# vim fac.sh
#!/bin/bash
show_menu(){
cat <<EOF
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)
EOF
}
while :
do
show_menu
read -p "请选择:" choice
case $choice in
d)
echo "===========disk info============"
df -hT
;;
m)
echo "===========mem info============="
free -m
;;
c)
echo "===========cpu info============="
uptime
;;
q)
break
;;
*)

;;
esac
done

[root@localhost ~]# bash fac.sh
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)
请选择:m
===========mem info=============
              total        used        free      shared  buff/cache   available
Mem:           1980         351        1200           9         428        1458
Swap:          2047           0        2047
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)
请选择:q

2.示例2:阶乘函数(传参:位置参数)

[root@localhost ~]# vim fun1.sh
#!/bin/bash
#定义函数名fun1
fun1(){
#定义阶乘元数
factorial=1
#使阶乘循环
for((i=1;i<=$1;i++))
do
#阶乘公式
factorial=$[$factorial*$i]
done
#输出阶乘结果
echo "$1的阶乘是:$factorial"
}
fun1 $1  //调用函数位置传参
fun1 $2
fun1 $3

[root@localhost ~]# bash fun1.sh 5 6 7
5的阶乘是:120
6的阶乘是:720
7的阶乘是:5040

3.示例3:函数传参 数组传参
(1)实现加法

[root@localhost ~]# vim 1.sh
num=(1 2 3)
array(){
for i in $*   //$*指1、2、3
do
expr $i + 5  //加法运算
done
}
array ${num[*]} //array函数调用  ${num[*]}为参数

[root@localhost ~]# bash 1.sh
6
7
8

(2)实现阶乘

[root@localhost ~]# vim fun3.sh
#!/bin/bash
num=(1 2 3)
num2=(2 3 4)
array(){
factorial=1
for i in $*
do
factorial=$[factorial * $i]
done
echo $factorial
}
array ${num[*]}
array ${num2[*]}

[root@localhost ~]# bash fun3.sh
6
24

4.示例4:函数结果 赋予数组

[root@localhost ~]# vim 3.sh
#!/bin/bash
num=(1 2 3)  //定义数组num
array(){     //定义函数
local j       
for i in $*
do
outarray[j++]=$[$i+5]
done
echo "${outarray[*]}"
}
result=` array ${num[*]} `
echo ${result[*]}

[root@localhost ~]# bash 3.sh
6 7 8
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值