shell的函数

时间:2020-04-15 18:15:48   收藏:0   阅读:77

函数的作用

1)命令的集合 完成特定功能的代码块
2)函数的优势可以使代码完全的模块化 便于复用 加强可读 易于修改
3)函数和变量类似 先定义才可调用,如果定义不调用则不执行

定义函数
函数的传参
函数内的变量
返回值      return

定义函数

#!/bin/sh
fun1(){
        echo "第一种定义方式"
}

function fun2 {
        echo "第二种定义方式"
}

function fun3() {
        echo "第三种定义方式"
}
fun1            # 调用函数非常简单 只需要写函数名即可
fun2
fun3

 

函数传参

1)函数名称后面跟字符串传参
[root@shell day5]# cat fun.sh 
#!/bin/sh
fun(){
     if [ -f $2 ];then
        echo "$2 exists"
     else
        return 5
     fi
}
fun /etc/hosts /etc/passwd

 


2)使用脚本的参数传参
[root@shell day5]# cat fun.sh
#!/bin/sh
fun(){
     if [ -f $1 ];then
        echo "$1 exists"
     else
        return 5
     fi
}
fun $2 $1
[root@shell day5]# sh fun.sh /etc/hosts /etc/passwd
/etc/passwd exists

 

思考:

#!/bin/sh
fun(){
        num=10
        for i in `seq 10`
        do
           total=$[$i+$num]
        done
        echo "total的结果是: $total"
}
fun

 

传参

#!/bin/sh
#第一种定义方式
fun(){
        num=$1
        for i in `seq 10`
        do
           total=$[$i+$num]
        done
        echo "total的结果是: $total"
}
fun $2 $1
[root@shell day5]# sh fun.sh 20 30
total的结果是: 40

 

函数的变量

local num=20 只针对当前的函数生效 其他函数和语句无法接收local的变量

函数的返回值

#!/bin/sh
fun(){
      echo 100
      return 1
}
result=`fun`
echo "函数的状态码是: $?"
echo "函数的执行结果是: $result"

注意: $?上一条执行的如果有函数名称 则返回函数内的return值 如果不相关则上一条命令的返回值

 

#!/bin/sh
fun(){
      if [ -f $1 ];then
         return 50
      else
         return 100
      fi
}
fun $1
#根据函数的返回状态码进行输出结果
re=$?
#[ $re -eq 50 ] && echo "文件存在"
#[ $re -eq 100 ] && echo "文件不存在"
if [ $re -eq 50 ];then
        echo "文件存在"
elif [ $re -eq 100 ];then
        echo "文件不存在"
fi

 

案例: 文件统计行
line 内置变量 按行读取

[root@shell day5]# wc -l /etc/passwd
37 /etc/passwd
[root@shell day5]# cat /etc/passwd|wc -l
37
[root@shell day5]# cat while1.sh 
#!/bin/h
while read line
do
      let i++       
done</etc/passwd
echo $i


awk {print NR} /etc/passwd

sed = /etc/passwd|xargs -n2

grep -n . /etc/passwd

less -N /etc/passwd

cat -n /etc/passwd
 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!