Skip to content

函数定义

基本语法

方式一:使用 function 关键字

bash
function function_name {
    commands
}

方式二:不使用 function 关键字

bash
function_name() {
    commands
}

基本示例

简单函数

bash
#!/bin/bash

# 定义函数
say_hello() {
    echo "Hello, World!"
}

# 调用函数
say_hello

带参数的函数

bash
#!/bin/bash

# 定义带参数的函数
greet() {
    echo "Hello, $1!"
}

# 调用函数
greet "张三"
greet "李四"

带返回值的函数

bash
#!/bin/bash

# 定义带返回值的函数
add() {
    echo $(($1 + $2))
}

# 调用函数并获取返回值
result=$(add 10 20)
echo "10 + 20 = $result"

函数参数

位置参数

bash
#!/bin/bash

# 定义函数
print_args() {
    echo "第一个参数: $1"
    echo "第二个参数: $2"
    echo "第三个参数: $3"
    echo "所有参数: $@"
    echo "参数个数: $#"
}

# 调用函数
print_args "apple" "banana" "orange"

特殊参数

bash
#!/bin/bash

# 定义函数
special_params() {
    echo "所有参数: $@"
    echo "所有参数(作为单个字符串): $*"
    echo "参数个数: $#"
    echo "脚本名称: $0"
}

# 调用函数
special_params "a" "b" "c"

处理可变参数

bash
#!/bin/bash

# 定义处理可变参数的函数
sum() {
    local total=0
    for num in "$@"; do
        total=$((total + num))
    done
    echo $total
}

# 调用函数
result=$(sum 1 2 3 4 5)
echo "1 + 2 + 3 + 4 + 5 = $result"

函数返回值

使用 echo 返回值

bash
#!/bin/bash

# 定义函数
get_date() {
    date '+%Y-%m-%d'
}

# 调用函数
current_date=$(get_date)
echo "当前日期: $current_date"

使用 return 返回状态码

bash
#!/bin/bash

# 定义函数
check_number() {
    if [ $1 -gt 0 ]; then
        return 0  # 成功
    else
        return 1  # 失败
    fi
}

# 调用函数
check_number 10
if [ $? -eq 0 ]; then
    echo "数字大于 0"
else
    echo "数字不大于 0"
fi

同时返回值和状态码

bash
#!/bin/bash

# 定义函数
divide() {
    if [ $2 -eq 0 ]; then
        echo "错误: 除数不能为 0"
        return 1
    fi
    echo $(($1 / $2))
    return 0
}

# 调用函数
result=$(divide 10 2)
status=$?

if [ $status -eq 0 ]; then
    echo "结果: $result"
else
    echo "$result"
fi

函数调用

直接调用

bash
#!/bin/bash

# 定义函数
say_hello() {
    echo "Hello, World!"
}

# 直接调用
say_hello

在条件语句中调用

bash
#!/bin/bash

# 定义函数
is_positive() {
    [ $1 -gt 0 ]
}

# 在条件语句中调用
if is_positive 10; then
    echo "数字是正数"
else
    echo "数字不是正数"
fi

在循环中调用

bash
#!/bin/bash

# 定义函数
process_item() {
    echo "处理: $1"
}

# 在循环中调用
for item in apple banana orange; do
    process_item "$item"
done

函数嵌套

基本嵌套

bash
#!/bin/bash

# 定义外部函数
outer() {
    echo "外部函数"
    
    # 定义内部函数
    inner() {
        echo "内部函数"
    }
    
    # 调用内部函数
    inner
}

# 调用外部函数
outer

相互调用

bash
#!/bin/bash

# 定义函数 A
func_a() {
    echo "函数 A"
    func_b
}

# 定义函数 B
func_b() {
    echo "函数 B"
}

# 调用函数 A
func_a

实用示例

示例1:计算器函数

bash
#!/bin/bash

# 加法函数
add() {
    echo $(($1 + $2))
}

# 减法函数
subtract() {
    echo $(($1 - $2))
}

# 乘法函数
multiply() {
    echo $(($1 * $2))
}

# 除法函数
divide() {
    if [ $2 -eq 0 ]; then
        echo "错误: 除数不能为 0"
        return 1
    fi
    echo $(($1 / $2))
}

# 使用函数
result=$(add 10 20)
echo "10 + 20 = $result"

result=$(subtract 20 10)
echo "20 - 10 = $result"

result=$(multiply 10 20)
echo "10 * 20 = $result"

result=$(divide 20 10)
echo "20 / 10 = $result"

示例2:字符串处理函数

bash
#!/bin/bash

# 转换为大写
to_upper() {
    echo "$1" | tr '[:lower:]' '[:upper:]'
}

# 转换为小写
to_lower() {
    echo "$1" | tr '[:upper:]' '[:lower:]'
}

# 反转字符串
reverse() {
    echo "$1" | rev
}

# 获取字符串长度
string_length() {
    echo ${#1}
}

# 使用函数
str="Hello World"

echo "原字符串: $str"
echo "大写: $(to_upper "$str")"
echo "小写: $(to_lower "$str")"
echo "反转: $(reverse "$str")"
echo "长度: $(string_length "$str")"

示例3:文件操作函数

bash
#!/bin/bash

# 检查文件是否存在
file_exists() {
    [ -f "$1" ]
}

# 创建文件
create_file() {
    if file_exists "$1"; then
        echo "文件已存在: $1"
        return 1
    fi
    touch "$1"
    echo "文件创建成功: $1"
}

# 删除文件
delete_file() {
    if ! file_exists "$1"; then
        echo "文件不存在: $1"
        return 1
    fi
    rm "$1"
    echo "文件删除成功: $1"
}

# 使用函数
create_file "test.txt"
delete_file "test.txt"

示例4:日志函数

bash
#!/bin/bash

# 日志函数
log() {
    local level="$1"
    local message="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$level] $message"
}

# 信息日志
info() {
    log "INFO" "$1"
}

# 警告日志
warn() {
    log "WARN" "$1"
}

# 错误日志
error() {
    log "ERROR" "$1"
}

# 使用函数
info "程序启动"
warn "配置文件不存在"
error "连接失败"

最佳实践

1. 使用 local 变量

bash
# 好的做法
func() {
    local var="局部变量"
    echo "$var"
}

# 不好的做法
func() {
    var="局部变量"
    echo "$var"
}

2. 检查参数

bash
# 好的做法
func() {
    if [ $# -lt 1 ]; then
        echo "错误: 缺少参数"
        return 1
    fi
    echo "$1"
}

# 不好的做法
func() {
    echo "$1"
}

3. 返回适当的状态码

bash
# 好的做法
func() {
    if [ $1 -gt 0 ]; then
        return 0
    else
        return 1
    fi
}

# 不好的做法
func() {
    if [ $1 -gt 0 ]; then
        echo "成功"
    else
        echo "失败"
    fi
}

总结

函数定义的关键点:

  1. 基本语法function_name() { commands }
  2. 函数参数:使用 $1, $2, $@, $#
  3. 返回值:使用 echo 返回值,使用 return 返回状态码
  4. 函数调用:直接调用函数名
  5. 函数嵌套:在函数中定义和调用其他函数
  6. 最佳实践:使用 local 变量,检查参数,返回适当的状态码

下一节我们将学习函数参数的使用。