函数定义和调用
函数是shell脚本中自定义的一些列执行命令,一般来说函数应该设置有返回值(正确返回0,错误返回非0)。对于错误返回,可以定义返回其他非0正值来细化错误。
使用函数的好处是可以避免出现大量重复代码,增加了代码的可读性。
- 定义函数
- 调用函数
- 函数返回值
- 函数传参
-
先定义再调用
函数定义
function FUNCTION_NAME(){
command1
command2
}
或者
FUNCTION_NAME(){
command1
command2
}
第一个函数
[root@servicex script]# ./day05/hello_func.sh
welcome to use the second type to define function
[root@servicex script]# cat day05/hello_func.sh
#!/usr/bin/bash
#Desc:the first function
#Author:lalin
#Date:2020-04-27
function hello(){
echo "welcome to use the first type to define function"
}
hello2(){
echo "welcome to use the second type to define function"
}
hello2
写一个函数统计/etc/passwd有多少行
[root@servicex script]# ./day05/count_etc.sh
28
[root@servicex script]# cat day05/count_etc.sh
#!/usr/bin/bash
#Desc:the function can count lines of the /etc/passwd
#Author:lalin
#Date:2020-04-27
read_file=/etc/passwd
function count(){
i=0
while read line;do
let i++
done < $read_file
wait
echo $i
}
count
函数的返回值
函数的返回值又叫做函数的退出状态,实际上是一种通信方式。
[root@servicex script]# ./day05/return_func.sh
please input your file path: /etc/passwd
file exists
[root@servicex script]# ./day05/return_func.sh
please input your file path: /etc/sakjdkajsdlk
no such file
[root@servicex script]# cat day05/return_func.sh
#!/usr/bin/bash
#Desc: test function return value
#Author:lalin
#Date:2020-04-27
read -p "please input your file path: " file_path
function test_file(){
if [ -f $file_path ];then
return 0
else
return 1
fi
}
test_file
if [ $? -eq 0 ];then
echo "file exists"
else
echo "no such file"
fi
函数传参
[root@servicex script]# ./day06/parameter.sh /etc/passwd
file exists
[root@servicex script]# ./day06/parameter.sh /etc/passwda
no such file
[root@servicex script]# cat day06/parameter.sh
#!/usr/bin/bash
#Desc:
#Author:lalin
#Date:2020-04-28
function test(){
if [ -e $1 ];then
echo "file exists"
else
echo "no such file"
fi
}
test $1
向函数中传入参数1和参数2计算参数1的参数2次方
[root@servicex script]# ./day06/count.sh 2 4
16
[root@servicex script]# ./day06/count.sh 2 6
64
[root@servicex script]# cat day06/count.sh
#!/usr/bin/bash
#Desc:
#Author:lalin
#Date:2020-04-28
function count(){
num=$1
for ((i=0;i<$2;i++));do
if [ $i -eq 0 ];then
num=$1
else
let num=num*$1
fi
done
wait
echo $num
}
count $1 $2
指定位置参数值
除了脚本运行时传入脚本的位置参数外,还可以使用命令set来指定位置参数的值,又叫重置,一旦使用set设置了传入参数的值,脚本将忽略运行时传入的位置参数
[root@servicex script]./day06/set—_func.sh 1 2 3 4
parameter is 20
parameter is 20
parameter is 04
parameter is 28
[root@servicex script]# cat day06/set—_func.sh
#!/usr/bin/bash
#Desc:
#Author:lalin
#Date:2020-04-28
set 20 20 04 28
for i in $@;do
echo "parameter is $i"
done