关于 bash
面向开发者的 Bash 脚本参考,提供更安全脚本、变量、控制流、函数和错误处理的实用模式。
主要功能
- 01脚本模板与安全设置
- 02变量和默认值模式
- 03文件与字符串条件判断
- 04函数与日志记录
- 05清理陷阱与错误处理
适用场景
- 01开始编写 Bash 脚本
- 02处理失败与清理
- 03编写更安全的 Shell 条件判断
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ dralgorhythm/ claude-agentic-framework --skill bash安装后在 Claude Code 中输入/bash确认已加载。
详细介绍
Bash 脚本
脚本模板
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# Script description
# Usage: ./script.sh <arg1> <arg2>
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
main() {
local arg1="${1:-default}"
# Script logic here
echo "Running with: $arg1"
}
main "$@"
安全设置
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Catch pipe failures
set -x # Debug: print commands
变量
# Declaration
readonly CONST="immutable"
local var="function scoped"
# Default values
name="${1:-default}" # Use default if unset
name="${1:?Error: missing}" # Error if unset
# String operations
"${var^^}" # Uppercase
"${var,,}" # Lowercase
"${var#prefix}" # Remove prefix
"${var%suffix}" # Remove suffix
条件语句
# File tests
[[ -f "$file" ]] # Is file
[[ -d "$dir" ]] # Is directory
[[ -r "$file" ]] # Is readable
[[ -x "$file" ]] # Is executable
# String tests
[[ -z "$var" ]] # Is empty
[[ -n "$var" ]] # Is not empty
[[ "$a" == "$b" ]] # Equals
# Numeric tests
(( num > 5 )) # Greater than
(( num == 5 )) # Equals
函数
log() {
local level="$1"
local message="$2"
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $message" >&2
}
die() {
log "ERROR" "$1"
exit 1
}
require_command() {
command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}
错误处理
# Trap for cleanup
cleanup() {
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
# Catch errors
if ! result=$(some_command 2>&1); then
die "Command failed: $result"
fi
循环
# For loop
for item in "${array[@]}"; do
echo "$item"
done
# While read
while IFS= read -r line; do
echo "$line"
done < file.txt
# Process substitution
while read -r line; do
echo "$line"
done < <(command)
最佳实践
- 为所有变量加引号:
"$var" - 使用
[[,而不是[ - 在函数中使用
local - 使用
readonly声明常量 - 始终使用
set -euo pipefail - 使用 shellcheck 进行代码检查
评论
支持 Markdown