shell 函数

1、什么是函数

  • 1、一定功能代码的封装
  • 2、函数可以降低代码的冗余度,使代码整体结构更加美观。

2、定义函数的两种方式

1、使用 function 关键字
function hello(){
	echo "hello 1"
}

2、直接函数名
hello2(){
	echo "hello 2"
}

3、运行函数时,只需调用函数名即可,无需加括号
hello
hello2

3、简单函数代码

1、统计文件行数


FILE=/etc/passwd

function count(){
	local i=0
	while read line
	do
		let i++
	done < $FILE
	echo "$i"
}
count

2、数字判断,(存粹无聊)

c_num(){
read -p "请输入一个数字...." num
if [ $num -ge 0 -a $num -le 10 ];then
    return 1
elif [ $num -ge 10 -a $num -le 20 ];then
    return 2
elif [ $num -ge 20 -a $num -le 30 ];then
    return 3
else
    return 4
fi
}
c_num
if [ $? -eq 1 ];then
    echo "1 input"
elif [ $? -eq 2 ];then
    echo "2 input"
elif [ $? -eq 3 ];then
    echo "3 input"
else
    echo "4 input"
fi

4、函数传参

当函数可以传入参数时是的函数更加灵活和有扩展性。
1、简单代码表示函数传参

#!/bin/bash
count(){
if [ -f $1 ];then   #直接在函数体内部调用shell内置参数
    echo  "$1 该文件存在 "
else
    echo " $1 error"
fi
}

count $1 #如果使用了参数,在函数调用处,后面需要跟参数

[root@localhost ~]# bash b4.sh 123.txt #执行脚本时,会将脚本名后的参数传递到函数内部进行计算
123.txt 该文件存在

2、简单计算

#!/bin/bash
[ $# -ne 2 ] && echo "请输入两个参数..."

cal_num(){
    let  test="$1"*"$2"
    echo "第一个值是 $1"
    echo "第二个值是 $2"
    echo "乘积为 $test"
}
cal_num $1 $2

[root@localhost ~]# bash b5.sh 3 5
第一个值是 3
第二个值是 5
乘积为 15

3、多个值计算


#!/bin/bash
test=1
cal_num(){
    for i in $*
        do
        let test=$test*$i
        done
        echo $test
}
cal_num $*

[root@localhost ~]# bash b6.sh 1 2 3 4 5 6 7
5040

4、使用内置 set 关键字 在脚本内部设定参数

#!/bin/bash
set 1 2 3 4 5 6 7 8
count=0
for i in $*
do
    let count+=$i
done
echo $count
posted @ 2020-02-13 11:36  叶落西南  阅读(184)  评论(0编辑  收藏  举报