Shell 函数
定义与调用、参数、返回值、局部变量与递归。
Key Points函数内的 $1 是函数参数不是脚本参数;return 只能返回 0-255 的退出码,要返回值用 echo 再 $(...) 捕获。
定义与调用
Bash
greet() {
echo "hello, $1"
}
greet Alice
greet BobOutput
hello, Alice
hello, Bob参数
Bash
show() {
echo "count=$# first=$1 all=$*"
}
show a b cOutput
count=3 first=a all=a b c返回值
Bash
add() {
echo $(( $1 + $2 ))
}
sum=$(add 3 4)
echo "sum=$sum"
check() {
[ -f "$1" ] && return 0 || return 1
}
echo "ok" > demo.txt
if check demo.txt; then echo "exists"; fiOutput
sum=7
existsreturn is limited to 0-255 and means success/failure. To return data, echo it and capture with $( ).
局部变量
Bash
x="global"
f() {
local x="local"
echo "inside: $x"
}
f
echo "outside: $x"Output
inside: local
outside: globalWithout
local, variables leak globally and functions clobber each other — one of the hardest bugs to find. Always use local.递归
Bash
fact() {
if [ "$1" -le 1 ]; then
echo 1
else
echo $(( $1 * $(fact $(( $1 - 1 ))) ))
fi
}
echo "5! = $(fact 5)"Output
5! = 120库函数与返回值约定
Bash
log() { printf '[%s] %s\n' "$1" "$2"; }
log INFO "started"
log WARN "disk 90%"Output
[INFO] started
[WARN] disk 90%定义与调用
Bash
greet() {
echo "hello, $1"
}
greet Alice
greet BobOutput
hello, Alice
hello, Bob参数
Bash
show() {
echo "count=$# first=$1 all=$*"
}
show a b cOutput
count=3 first=a all=a b c返回值
Bash
add() {
echo $(( $1 + $2 ))
}
sum=$(add 3 4)
echo "sum=$sum"
check() {
[ -f "$1" ] && return 0 || return 1
}
echo "ok" > demo.txt
if check demo.txt; then echo "exists"; fiOutput
sum=7
existsreturn 只能返回 0-255,用来表示成功/失败;要返回字符串或大数字,就用 echo 输出,调用方用 $( ) 接。
局部变量
Bash
x="global"
f() {
local x="local"
echo "inside: $x"
}
f
echo "outside: $x"Output
inside: local
outside: global不加
local 的变量会污染全局,函数间互相覆盖,是 Shell 脚本最难查的 bug 之一。函数里定义的变量一律加 local。递归
Bash
fact() {
if [ "$1" -le 1 ]; then
echo 1
else
echo $(( $1 * $(fact $(( $1 - 1 ))) ))
fi
}
echo "5! = $(fact 5)"Output
5! = 120库函数与返回值约定
Bash
log() { printf '[%s] %s\n' "$1" "$2"; }
log INFO "started"
log WARN "disk 90%"Output
[INFO] started
[WARN] disk 90%