Shell之Function与Source
Shell之Function与Source
😄 Written by Zak Zhu
学习python风格, 优雅规范书写shell代码
参考
- 菜鸟教程/Shell 函数(https://www.runoob.com/linux/linux-shell-func.html)
- C语言中文网/Shell函数: Shell函数返回值, 删除函数, 在终端调用函数(http://c.biancheng.net/cpp/view/7011.html)
Fuction的编写
函数语法
定义格式:
[function] foo() {
COMMANDS
[return N] # 返回码(N)的取值范围: 0~255
}
调用格式:
foo [ARGS]
实例:
# Defined function
function hello() {
echo "Hello World !"
}
# Invoke function
hello
函数传参
实例:
function two_num_sum() {
let sum=$1+$2
return ${sum}
}
read -p "Please input the first number: " arg1
read -p "Please input the second number: " arg2
two_num_sum ${arg1} ${arg2}
ret=$?
echo "The sum of two numbers is ${ret}"
Source的使用
和其他语言一样, Shell也可以包含外部脚本. 这样可以很方便的封装一些公用的代码作为一个独立的文件.
实例:
-
functions.sh文件:
function hello() { echo "Hello World !" } function two_num_sum() { let sum=$1+$2 return ${sum} }
-
bin.sh文件:
#!/bin/bash ##################################### # @Author: # @Created Time: 2019-10-01 02:07:32 # @Description: ##################################### source ./functions.sh hello read -p "Please input the first number: " arg1 read -p "Please input the second number: " arg2 two_num_sum ${arg1} ${arg2} ret=$? echo "The sum of two numbers is ${ret}"
执行bin.sh的结果: