Shell 函数

定义与调用、参数、返回值、局部变量与递归。

Beginner
Key Points函数内的 $1 是函数参数不是脚本参数;return 只能返回 0-255 的退出码,要返回值用 echo 再 $(...) 捕获。

定义与调用

Bash
greet() {
    echo "hello, $1"
}
greet Alice
greet Bob
Output
hello, Alice
hello, Bob

参数

Bash
show() {
    echo "count=$# first=$1 all=$*"
}
show a b c
Output
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"; fi
Output
sum=7
exists

return 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: global
Without 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%

Friends & Partners