Shell 函数和脚本

学习函数定义、参数传递和脚本组织,构建模块化的 Shell 程序

函数基础

函数定义

# 方式1:使用function关键字
function greet() {
echo "Hello, $1!"
}
# 方式2:直接定义
greet() {
echo "Hello, $1!"
}
# 调用函数
greet "World"
greet "Linux"

函数特点

  • 提高代码复用性
  • 使脚本结构更清晰
  • 便于调试和维护
  • 支持参数传递和返回值

参数传递

函数参数

#!/bin/bash
calculate() {
local num1=$1
local num2=$2
local operation=$3
case $operation in
"add")
echo $((num1 + num2))
;;
"sub")
echo $((num1 - num2))
;;
*)
echo "不支持的操作"
return 1
;;
esac
}
# 调用函数
result=$(calculate 10 5 "add")
echo "结果: $result"

局部变量

#!/bin/bash
global_var="全局变量"
test_scope() {
local local_var="局部变量"
global_var="修改后的全局变量"
echo "函数内: $local_var"
echo "函数内: $global_var"
}
echo "调用前: $global_var"
test_scope
echo "调用后: $global_var"

返回值处理

return 语句

#!/bin/bash
is_file_exists() {
if [ -f "$1" ]; then
return 0 # 成功
else
return 1 # 失败
fi
}
# 检查返回值
if is_file_exists "/etc/passwd"; then
echo "文件存在"
else
echo "文件不存在"
fi

输出返回值

#!/bin/bash
get_timestamp() {
echo $(date +"%Y-%m-%d %H:%M:%S")
}
get_file_size() {
if [ -f "$1" ]; then
stat -c%s "$1"
else
echo "0"
fi
}
# 获取返回值
current_time=$(get_timestamp)
file_size=$(get_file_size "/etc/passwd")
echo "时间: $current_time"
echo "文件大小: $file_size 字节"

脚本组织

脚本结构

#!/bin/bash
# 脚本描述:系统监控工具
# 作者:Linux Cloud Lab
# 版本:1.0
# 日期:2025-12-15
# 全局变量
SCRIPT_NAME=$(basename "$0")
LOG_FILE="/var/log/monitor.log"
# 函数定义
show_usage() {
echo "用法: $SCRIPT_NAME [选项]"
echo "选项:"
echo " -h, --help 显示帮助信息"
echo " -v, --version 显示版本信息"
}
# 主程序
main() {
# 主要逻辑
echo "开始监控..."
}
# 脚本入口
if [ "$BASH_SOURCE[0]" = "$0" ]; then
main "$@"
fi

模块化设计

# 加载外部函数库
source /path/to/utils.sh
source /path/to/config.sh
# 或者检查文件是否存在
if [ -f "utils.sh" ]; then
source utils.sh
else
echo "错误: 找不到 utils.sh"
exit 1
fi

实用函数库

日志函数

#!/bin/bash
log() {
local level=$1
local message=$2
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE"
}
log_info() {
log "INFO" "$1"
}
log_error() {
log "ERROR" "$1" >&2
}
log_warn() {
log "WARN" "$1"
}

文件操作函数

#!/bin/bash
backup_file() {
local file=$1
local backup_dir=$2:-/backup
if [ -f "$file" ]; then
local filename=$(basename "$file")
local timestamp=$(date +%Y%m%d_%H%M%S)
cp "$file" "$backup_dir/$filename_$timestamp"
echo "备份完成: $backup_dir/$filename_$timestamp"
else
echo "错误: 文件 $file 不存在"
return 1
fi
}
cleanup_old_files() {
local dir=$1
local days=$2:-7
find "$dir" -type f -mtime +$days -delete
echo "清理完成: 删除 $days 天前的文件"
}

系统检查函数

#!/bin/bash
check_disk_space() {
local threshold=$1:-80
local usage=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
if [ $usage -gt $threshold ]; then
log_warn "磁盘使用率过高: $usage%"
return 1
else
log_info "磁盘使用率正常: $usage%"
return 0
fi
}
check_service() {
local service=$1
if systemctl is-active --quiet "$service"; then
log_info "服务 $service 运行正常"
return 0
else
log_error "服务 $service 未运行"
return 1
fi
}

继续学习

掌握了函数和脚本后,继续学习更多高级技能