01. 函数定义
Bash 函数用于组织可重用的代码。函数可以接收参数、返回值。
bash
# 定义函数
greet() {
echo "Hello, $1!"
}
# 调用函数
greet "Alice" # Hello, Alice!
# 函数参数
show_info() {
echo "第一个参数: $1"
echo "所有参数: $@"
echo "参数个数: $#"
}
# 通过 echo 返回值
add() {
echo $(( $1 + $2 ))
}
RESULT=$(add 3 5)
echo "3 + 5 = $RESULT"02. 局部变量
Bash 函数中的变量默认是全局的。使用 local 关键字声明局部变量,避免变量污染。
bash
# 使用 local
process_data() {
local input="$1"
local result=""
result=$(echo "$input" | tr '[:upper:]' '[:lower:]')
echo "$result"
}
OUTPUT=$(process_data "HELLO")
echo "$OUTPUT" # hello
# 递归函数
factorial() {
if [ "$1" -le 1 ]; then
echo 1
else
local prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
echo "5! = $(factorial 5)" # 120知识测验
第 1/4 题正确 0
Bash 函数中 local 关键字的作用是什么?
下一节
下一节 输入输出与重定向