【008】Linux Shell学习笔记-函数
1 函数
1.1 定义
函数是完成某个特定功能的一段代码
函数不能独立运行, 需要使用时通过函数名调用函数。
function_name(){
list of commands
[ return value ]
}
1.2 调用
直接使用函数名即可调用函数。
例1:用函数写一个添加一个固定用户的脚本,然后在脚本中调用它
#!/bin/bash
USERADD() { # 定义函数
user_name=test1
if id $user_name &> /dev/null
then
echo "User $user_name exist"
else
useradd $user_name
echo "user $user_name added"
fi
}
USERADD # 调用函数
例2:
#!/bin/bash
funWithReturn(){
echo "The function is to get the sum of two numbers..."
echo -n "Input first number:"
read aNum
echo -n "Input another number:"
read anotherNum
echo "The two numbers are $aNum and $anotherNum!"
return $(($aNum + $anotherNum))
}
funWithReturn
ret=$?
echo "The sum of two numbers is $ret!"
1.3 自定义函数状态返回值
当我们需要函数执行完成后给出返回值,不能用exit,要使用return。return被执行后,函数运行结束,return后面的代码将不再执行。
如果不加,会将最后一条命令运行结果作为返回值。Shell函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他表示失败。如果return其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”。
如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。
1.4 函数的传参
函数是一种特殊的命令,在执行时,也可以向函数体内传递参数。同shell脚本的位置参数。
1.5 函数中的变量
全局变量:直接定义,在整个脚本中生效。
局部变量:在函数中使用local定义,局部变量仅在函数内生效。
2 实例
3 练习题
- 写一个power函数,调用时可接一个数字参数,得到的结果是此参数的平方(需要对参数有判断功能)。
#!/bin/bash
Power(){
!expr $1 &> /dev/null && echo "必须是数字参数" && exit
echo " 平方是"
echo $[$1*$1]
}
Power $1
- 改写上面的函数,调用时接两个参数(如x和y),执行结果为x的y次方。
#!/bin/bash
power(){
!expr $1 +$2 &> /dev/null && echo "必须是两个数字参数" && exit
echo $[$1**$2]
}
power $1 $2
- 写一个脚本,执行后生成一个随机UUID。(不得使用uuidgen命令)
UUID示例如下:
4aa16368-b383-433c-825f-a6ccc6318850
0d42e4aa-490c-4d43-8eb7-992dd0eb8ef6
48451063-9bf7-4079-89dd-e47cc7408e7e
方法一
char=({a..f} {0..9})
len=${#char[*]}
UUID=
uuid1=
uuid2=
uuid3=
uuid4=
for i in {0..8};do
index=$[RANDOM%len]
uuid1=$uuid1${char[index]}
done
for i in {0..4};do
index=$[RANDOM%len]
uuid2=$uuid2${char[index]}
done
for i in {0..4};do
index=$[RANDOM%len]
uuid3=$uuid3${char[index]}
done
for i in {0..4};do
index=$[RANDOM%len]
uuid4=$uuid4${char[index]}
done
for i in {0..12};do
index=$[RANDOM%len]
uuid5=$uuid5${char[index]}
done
echo "uuid is $uuid1-$uuid2-$uuid3-$uuid4-$uuid5"
}
RandomUUID
方法二:传参的方法
#!/bin/bash
RANUU(){
chars=({0..9}{a..f})
for i in $seq $1);do
index=$[RANDOM%16]
echo -n ${chars[index]}
done
}
echo $(RANUU 8)-$(RANUU 4)-$(RANUU 4)-$(RANUU 4)-$(RANUU 4)-$(RANUU 12)
Reference
- Linux Shell之函数 by 清风自来&静等花开
- 课堂笔记