debugging-troubleshooting-2025
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese🚨 CRITICAL GUIDELINES
🚨 重要指南
Windows File Path Requirements
Windows文件路径要求
MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes () in file paths, NOT forward slashes ().
\/Examples:
- ❌ WRONG:
D:/repos/project/file.tsx - ✅ CORRECT:
D:\repos\project\file.tsx
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
强制要求:在Windows系统中始终使用反斜杠表示文件路径
在Windows系统上使用Edit或Write工具时,文件路径必须使用反斜杠(),而不能使用正斜杠()。
\/示例:
- ❌ 错误:
D:/repos/project/file.tsx - ✅ 正确:
D:\repos\project\file.tsx
此要求适用于:
- Edit工具的file_path参数
- Write工具的file_path参数
- Windows系统上的所有文件操作
Documentation Guidelines
文档编写指南
NEVER create new documentation files unless explicitly requested by the user.
- Priority: Update existing README.md files rather than creating new documentation
- Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
- Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
- User preference: Only create additional .md files when user specifically asks for documentation
除非用户明确要求,否则切勿创建新的文档文件。
- 优先级:优先更新现有README.md文件,而非创建新文档
- 仓库整洁性:保持仓库根目录整洁——除非用户要求,否则仅保留README.md
- 风格:文档应简洁、直接、专业——避免AI生成的语气
- 用户偏好:仅当用户明确要求文档时,才创建额外的.md文件
Bash Debugging & Troubleshooting (2025)
Bash脚本调试与故障排除(2025版)
Overview
概述
Comprehensive debugging techniques and troubleshooting patterns for bash scripts following 2025 best practices.
遵循2025年最佳实践的Bash脚本全面调试技术与故障排除模式。
Debug Mode Techniques
调试模式技术
1. Basic Debug Mode (set -x)
1. 基础调试模式(set -x)
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailEnable debug mode
Enable debug mode
set -x
set -x
Your commands here
Your commands here
command1
command2
command1
command2
Disable debug mode
Disable debug mode
set +x
set +x
Continue without debug
Continue without debug
command3
undefinedcommand3
undefined2. Enhanced Debug Output (PS4)
2. 增强型调试输出(PS4)
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailCustom debug prompt with file:line:function
Custom debug prompt with file:line:function
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
set -x
my_function() {
local var="value"
echo "$var"
}
my_function
set +x
**Output:**+(script.sh:10): my_function(): local var=value
+(script.sh:11): my_function(): echo value
value
undefinedexport PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
set -x
my_function() {
local var="value"
echo "$var"
}
my_function
set +x
**输出结果:**+(script.sh:10): my_function(): local var=value
+(script.sh:11): my_function(): echo value
value
undefined3. Conditional Debugging
3. 条件式调试
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailEnable via environment variable
Enable via environment variable
DEBUG="${DEBUG:-false}"
debug() {
if [[ "$DEBUG" == "true" ]]; then
echo "[DEBUG] $*" >&2
fi
}
DEBUG="${DEBUG:-false}"
debug() {
if [[ "$DEBUG" == "true" ]]; then
echo "[DEBUG] $*" >&2
fi
}
Usage
Usage
debug "Starting process"
process_data
debug "Process complete"
debug "Starting process"
process_data
debug "Process complete"
Run: DEBUG=true ./script.sh
Run: DEBUG=true ./script.sh
undefinedundefined4. Debugging Specific Functions
4. 特定函数调试
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailDebug wrapper
Debug wrapper
debug_function() {
local func_name="$1"
shift
echo "[TRACE] Calling: $func_name $*" >&2
set -x
"$func_name" "$@"
local exit_code=$?
set +x
echo "[TRACE] Exit code: $exit_code" >&2
return $exit_code}
debug_function() {
local func_name="$1"
shift
echo "[TRACE] Calling: $func_name $*" >&2
set -x
"$func_name" "$@"
local exit_code=$?
set +x
echo "[TRACE] Exit code: $exit_code" >&2
return $exit_code}
Usage
Usage
my_complex_function() {
local arg1="$1"
# Complex logic
echo "Result: $arg1"
}
debug_function my_complex_function "test"
undefinedmy_complex_function() {
local arg1="$1"
# Complex logic
echo "Result: $arg1"
}
debug_function my_complex_function "test"
undefinedTracing and Profiling
追踪与性能分析
1. Execution Time Profiling
1. 执行时间分析
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailProfile function execution time
Profile function execution time
profile() {
local start_ns end_ns duration_ms
start_ns=$(date +%s%N)
"$@"
local exit_code=$?
end_ns=$(date +%s%N)
duration_ms=$(( (end_ns - start_ns) / 1000000 ))
echo "[PROFILE] '$*' took ${duration_ms}ms (exit: $exit_code)" >&2
return $exit_code}
profile() {
local start_ns end_ns duration_ms
start_ns=$(date +%s%N)
"$@"
local exit_code=$?
end_ns=$(date +%s%N)
duration_ms=$(( (end_ns - start_ns) / 1000000 ))
echo "[PROFILE] '$*' took ${duration_ms}ms (exit: $exit_code)" >&2
return $exit_code}
Usage
Usage
profile slow_command arg1 arg2
undefinedprofile slow_command arg1 arg2
undefined2. Function Call Tracing
2. 函数调用追踪
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailTrace all function calls
Trace all function calls
trace_on() {
set -o functrace
trap 'echo "[TRACE] ${FUNCNAME[0]}() called from ${BASH_SOURCE[1]}:${BASH_LINENO[0]}" >&2' DEBUG
}
trace_off() {
set +o functrace
trap - DEBUG
}
trace_on() {
set -o functrace
trap 'echo "[TRACE] ${FUNCNAME[0]}() called from ${BASH_SOURCE[1]}:${BASH_LINENO[0]}" >&2' DEBUG
}
trace_off() {
set +o functrace
trap - DEBUG
}
Usage
Usage
trace_on
function1
function2
trace_off
undefinedtrace_on
function1
function2
trace_off
undefined3. Variable Inspection
3. 变量检查
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailInspect all variables at any point
Inspect all variables at any point
inspect_vars() {
echo "=== Variable Dump ===" >&2
declare -p | grep -v "^declare -[^ ]*r " | sort >&2
echo "===================" >&2
}
inspect_vars() {
echo "=== Variable Dump ===" >&2
declare -p | grep -v "^declare -[^ ]*r " | sort >&2
echo "===================" >&2
}
Inspect specific variable
Inspect specific variable
inspect_var() {
local var_name="$1"
echo "[INSPECT] $var_name = ${!var_name:-<unset>}" >&2
}
inspect_var() {
local var_name="$1"
echo "[INSPECT] $var_name = ${!var_name:-<unset>}" >&2
}
Usage
Usage
my_var="test"
inspect_var my_var
inspect_vars
undefinedmy_var="test"
inspect_var my_var
inspect_vars
undefinedError Handling and Recovery
错误处理与恢复
1. Trap-Based Error Handler
1. 基于Trap的错误处理器
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailComprehensive error handler
Comprehensive error handler
error_handler() {
local exit_code=$?
local line_number=$1
echo "ERROR: Command failed with exit code $exit_code" >&2
echo " File: ${BASH_SOURCE[1]}" >&2
echo " Line: $line_number" >&2
echo " Function: ${FUNCNAME[1]:-main}" >&2
# Print stack trace
local frame=0
while caller $frame; do
((frame++))
done >&2
exit "$exit_code"}
trap 'error_handler $LINENO' ERR
error_handler() {
local exit_code=$?
local line_number=$1
echo "ERROR: Command failed with exit code $exit_code" >&2
echo " File: ${BASH_SOURCE[1]}" >&2
echo " Line: $line_number" >&2
echo " Function: ${FUNCNAME[1]:-main}" >&2
# Print stack trace
local frame=0
while caller $frame; do
((frame++))
done >&2
exit "$exit_code"}
trap 'error_handler $LINENO' ERR
Your script logic
Your script logic
risky_command
undefinedrisky_command
undefined2. Dry-Run Mode
2. 试运行模式
bash
#!/usr/bin/env bash
set -euo pipefail
DRY_RUN="${DRY_RUN:-false}"bash
#!/usr/bin/env bash
set -euo pipefail
DRY_RUN="${DRY_RUN:-false}"Safe execution wrapper
Safe execution wrapper
execute() {
if [[ "$DRY_RUN" == "true" ]]; then
echo "[DRY-RUN] Would execute: $*" >&2
return 0
else
"$@"
fi
}
execute() {
if [[ "$DRY_RUN" == "true" ]]; then
echo "[DRY-RUN] Would execute: $*" >&2
return 0
else
"$@"
fi
}
Usage
Usage
execute rm -rf /tmp/data
execute cp file.txt backup/
execute rm -rf /tmp/data
execute cp file.txt backup/
Run: DRY_RUN=true ./script.sh
Run: DRY_RUN=true ./script.sh
undefinedundefined3. Rollback on Failure
3. 失败时回滚
bash
#!/usr/bin/env bash
set -euo pipefail
OPERATIONS=()bash
#!/usr/bin/env bash
set -euo pipefail
OPERATIONS=()Track operations for rollback
Track operations for rollback
track_operation() {
local rollback_cmd="$1"
OPERATIONS+=("$rollback_cmd")
}
track_operation() {
local rollback_cmd="$1"
OPERATIONS+=("$rollback_cmd")
}
Execute rollback
Execute rollback
rollback() {
echo "Rolling back operations..." >&2
for ((i=${#OPERATIONS[@]}-1; i>=0; i--)); do
echo " Executing: ${OPERATIONS[$i]}" >&2
eval "${OPERATIONS[$i]}" || true
done
}
trap rollback ERR EXIT
rollback() {
echo "Rolling back operations..." >&2
for ((i=${#OPERATIONS[@]}-1; i>=0; i--)); do
echo " Executing: ${OPERATIONS[$i]}" >&2
eval "${OPERATIONS[$i]}" || true
done
}
trap rollback ERR EXIT
Example usage
Example usage
mkdir /tmp/mydir
track_operation "rmdir /tmp/mydir"
touch /tmp/mydir/file.txt
track_operation "rm /tmp/mydir/file.txt"
mkdir /tmp/mydir
track_operation "rmdir /tmp/mydir"
touch /tmp/mydir/file.txt
track_operation "rm /tmp/mydir/file.txt"
If script fails, rollback executes automatically
If script fails, rollback executes automatically
undefinedundefinedCommon Issues and Solutions
常见问题与解决方案
1. Script Works Interactively but Fails in Cron
1. 脚本在交互式环境中正常运行但在Cron中失败
Problem: Script runs fine manually but fails when scheduled.
Solution:
bash
#!/usr/bin/env bash
set -euo pipefail问题: 脚本手动运行正常,但定时调度时失败。
解决方案:
bash
#!/usr/bin/env bash
set -euo pipefailFix PATH for cron
Fix PATH for cron
export PATH="/usr/local/bin:/usr/bin:/bin"
export PATH="/usr/local/bin:/usr/bin:/bin"
Set working directory
Set working directory
cd "$(dirname "$0")" || exit 1
cd "$(dirname "$0")" || exit 1
Log everything for debugging
Log everything for debugging
exec 1>> /var/log/myscript.log 2>&1
echo "[$(date)] Script starting"
exec 1>> /var/log/myscript.log 2>&1
echo "[$(date)] Script starting"
Your commands here
Your commands here
echo "[$(date)] Script complete"
undefinedecho "[$(date)] Script complete"
undefined2. Whitespace in Filenames Breaking Script
2. 文件名中的空格导致脚本失败
Problem: Script fails when processing files with spaces.
Debugging:
bash
#!/usr/bin/env bash
set -euo pipefail问题: 处理包含空格的文件时脚本失败。
调试方法:
bash
#!/usr/bin/env bash
set -euo pipefailShow exactly what the script sees
Show exactly what the script sees
debug_filename() {
local filename="$1"
echo "Filename: '$filename'" >&2
echo "Length: ${#filename}" >&2
hexdump -C <<< "$filename" >&2
}
debug_filename() {
local filename="$1"
echo "Filename: '$filename'" >&2
echo "Length: ${#filename}" >&2
hexdump -C <<< "$filename" >&2
}
Proper handling
Proper handling
while IFS= read -r -d '' file; do
debug_filename "$file"
# Process "$file"
done < <(find . -name "*.txt" -print0)
undefinedwhile IFS= read -r -d '' file; do
debug_filename "$file"
# Process "$file"
done < <(find . -name "*.txt" -print0)
undefined3. Script Behaves Differently on Different Systems
3. 脚本在不同系统上表现不一致
Problem: Works on Linux but fails on macOS.
Debugging:
bash
#!/usr/bin/env bash
set -euo pipefail问题: 在Linux上正常运行,但在macOS上失败。
调试方法:
bash
#!/usr/bin/env bash
set -euo pipefailPlatform detection and debugging
Platform detection and debugging
detect_platform() {
echo "=== Platform Info ===" >&2
echo "OS: $OSTYPE" >&2
echo "Bash: $BASH_VERSION" >&2
echo "PATH: $PATH" >&2
# Check tool versions
for tool in sed awk grep; do
if command -v "$tool" &> /dev/null; then
echo "$tool: $($tool --version 2>&1 | head -1)" >&2
fi
done
echo "====================" >&2}
detect_platform
detect_platform() {
echo "=== Platform Info ===" >&2
echo "OS: $OSTYPE" >&2
echo "Bash: $BASH_VERSION" >&2
echo "PATH: $PATH" >&2
# Check tool versions
for tool in sed awk grep; do
if command -v "$tool" &> /dev/null; then
echo "$tool: $($tool --version 2>&1 | head -1)" >&2
fi
done
echo "====================" >&2}
detect_platform
Use portable patterns
Use portable patterns
case "$OSTYPE" in
linux*) SED_CMD="sed" ;;
darwin*) SED_CMD=$(command -v gsed || echo sed) ;;
*) echo "Unknown platform" >&2; exit 1 ;;
esac
undefinedcase "$OSTYPE" in
linux*) SED_CMD="sed" ;;
darwin*) SED_CMD=$(command -v gsed || echo sed) ;;
*) echo "Unknown platform" >&2; exit 1 ;;
esac
undefined4. Variable Scope Issues
4. 变量作用域问题
Problem: Variables not available where expected.
Debugging:
bash
#!/usr/bin/env bash
set -euo pipefail问题: 变量在预期的位置不可用。
调试方法:
bash
#!/usr/bin/env bash
set -euo pipefailShow variable scope
Show variable scope
test_scope() {
local local_var="local"
global_var="global"
echo "Inside function:" >&2
echo " local_var=$local_var" >&2
echo " global_var=$global_var" >&2}
test_scope
echo "Outside function:" >&2
echo " local_var=${local_var:-<not set>}" >&2
echo " global_var=${global_var:-<not set>}" >&2
test_scope() {
local local_var="local"
global_var="global"
echo "Inside function:" >&2
echo " local_var=$local_var" >&2
echo " global_var=$global_var" >&2}
test_scope
echo "Outside function:" >&2
echo " local_var=${local_var:-<not set>}" >&2
echo " global_var=${global_var:-<not set>}" >&2
Subshell scope issue
Subshell scope issue
echo "test" | (
read -r value
echo "In subshell: $value"
)
echo "After subshell: ${value:-<not set>}" # Empty!
undefinedecho "test" | (
read -r value
echo "In subshell: $value"
)
echo "After subshell: ${value:-<not set>}" # Empty!
undefinedInteractive Debugging
交互式调试
1. Breakpoint Pattern
1. 断点模式
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailInteractive breakpoint
Interactive breakpoint
breakpoint() {
local message="${1:-Breakpoint}"
echo "$message" >&2
echo "Variables:" >&2
declare -p | grep -v "^declare -[^ ]*r " >&2
read -rp "Press Enter to continue, 'i' for inspect: " choice
if [[ "$choice" == "i" ]]; then
bash # Drop into interactive shell
fi}
breakpoint() {
local message="${1:-Breakpoint}"
echo "$message" >&2
echo "Variables:" >&2
declare -p | grep -v "^declare -[^ ]*r " >&2
read -rp "Press Enter to continue, 'i' for inspect: " choice
if [[ "$choice" == "i" ]]; then
bash # Drop into interactive shell
fi}
Usage
Usage
value=42
breakpoint "Before critical operation"
critical_operation "$value"
undefinedvalue=42
breakpoint "Before critical operation"
critical_operation "$value"
undefined2. Watch Mode (Continuous Debugging)
2. 监控模式(持续调试)
bash
#!/usr/bin/env bashbash
#!/usr/bin/env bashWatch script execution in real-time
Watch script execution in real-time
watch_script() {
local script="$1"
shift
while true; do
clear
echo "=== Running: $script $* ==="
echo "=== $(date) ==="
bash -x "$script" "$@" 2>&1 | tail -50
sleep 2
done}
watch_script() {
local script="$1"
shift
while true; do
clear
echo "=== Running: $script $* ==="
echo "=== $(date) ==="
bash -x "$script" "$@" 2>&1 | tail -50
sleep 2
done}
Usage: watch_script myscript.sh arg1 arg2
Usage: watch_script myscript.sh arg1 arg2
undefinedundefinedLogging Best Practices
日志最佳实践
1. Structured Logging
1. 结构化日志
bash
#!/usr/bin/env bash
set -euo pipefail
readonly LOG_FILE="${LOG_FILE:-/var/log/myscript.log}"
log() {
local level="$1"
shift
local timestamp
timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "${timestamp} [${level}] $*" | tee -a "$LOG_FILE" >&2
}
log_info() { log "INFO" "$@"; }
log_warn() { log "WARN" "$@"; }
log_error() { log "ERROR" "$@"; }
log_debug() { [[ "${DEBUG:-false}" == "true" ]] && log "DEBUG" "$@"; }bash
#!/usr/bin/env bash
set -euo pipefail
readonly LOG_FILE="${LOG_FILE:-/var/log/myscript.log}"
log() {
local level="$1"
shift
local timestamp
timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "${timestamp} [${level}] $*" | tee -a "$LOG_FILE" >&2
}
log_info() { log "INFO" "$@"; }
log_warn() { log "WARN" "$@"; }
log_error() { log "ERROR" "$@"; }
log_debug() { [[ "${DEBUG:-false}" == "true" ]] && log "DEBUG" "$@"; }Usage
Usage
log_info "Starting process"
log_debug "Debug info"
log_error "Something failed"
undefinedlog_info "Starting process"
log_debug "Debug info"
log_error "Something failed"
undefined2. Log Rotation Awareness
2. 日志轮转感知
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailEnsure log file exists and is writable
Ensure log file exists and is writable
setup_logging() {
local log_file="${1:-/var/log/myscript.log}"
local log_dir
log_dir=$(dirname "$log_file")
if [[ ! -d "$log_dir" ]]; then
mkdir -p "$log_dir" || {
echo "Cannot create log directory: $log_dir" >&2
return 1
}
fi
if [[ ! -w "$log_dir" ]]; then
echo "Log directory not writable: $log_dir" >&2
return 1
fi
# Redirect all output to log
exec 1>> "$log_file"
exec 2>&1}
setup_logging
undefinedsetup_logging() {
local log_file="${1:-/var/log/myscript.log}"
local log_dir
log_dir=$(dirname "$log_file")
if [[ ! -d "$log_dir" ]]; then
mkdir -p "$log_dir" || {
echo "Cannot create log directory: $log_dir" >&2
return 1
}
fi
if [[ ! -w "$log_dir" ]]; then
echo "Log directory not writable: $log_dir" >&2
return 1
fi
# Redirect all output to log
exec 1>> "$log_file"
exec 2>&1}
setup_logging
undefinedPerformance Debugging
性能调试
1. Identify Slow Commands
1. 识别慢速命令
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailProfile each command in script
Profile each command in script
profile_script() {
export PS4='+ $(date +%s.%N) ${BASH_SOURCE}:${LINENO}: '
set -x
# Your commands here
command1
command2
command3
set +x}
profile_script() {
export PS4='+ $(date +%s.%N) ${BASH_SOURCE}:${LINENO}: '
set -x
# Your commands here
command1
command2
command3
set +x}
Analyze output:
Analyze output:
+ 1698765432.123456 script.sh:10: command1 (fast)
+ 1698765432.123456 script.sh:10: command1 (fast)
+ 1698765437.654321 script.sh:11: command2 (5 seconds - slow!)
+ 1698765437.654321 script.sh:11: command2 (5 seconds - slow!)
undefinedundefined2. Memory Usage Tracking
2. 内存使用追踪
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailTrack memory usage
Track memory usage
check_memory() {
local pid=${1:-$$}
ps -o pid,vsz,rss,comm -p "$pid" | tail -1
}
check_memory() {
local pid=${1:-$$}
ps -o pid,vsz,rss,comm -p "$pid" | tail -1
}
Monitor during execution
Monitor during execution
monitor_memory() {
while true; do
check_memory
sleep 1
done &
local monitor_pid=$!
# Your commands here
"$@"
kill "$monitor_pid" 2>/dev/null || true
wait "$monitor_pid" 2>/dev/null || true}
monitor_memory ./memory_intensive_task.sh
undefinedmonitor_memory() {
while true; do
check_memory
sleep 1
done &
local monitor_pid=$!
# Your commands here
"$@"
kill "$monitor_pid" 2>/dev/null || true
wait "$monitor_pid" 2>/dev/null || true}
monitor_memory ./memory_intensive_task.sh
undefinedTesting Patterns
测试模式
1. Unit Test Template
1. 单元测试模板
bash
#!/usr/bin/env bashbash
#!/usr/bin/env bashtest_functions.sh
test_functions.sh
Source the script to test
Source the script to test
source ./functions.sh
source ./functions.sh
Test counter
Test counter
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0
Assert function
Assert function
assert_equals() {
local expected="$1"
local actual="$2"
local test_name="${3:-Test}"
((TESTS_RUN++))
if [[ "$expected" == "$actual" ]]; then
echo "✓ $test_name" >&2
((TESTS_PASSED++))
else
echo "✗ $test_name" >&2
echo " Expected: $expected" >&2
echo " Actual: $actual" >&2
((TESTS_FAILED++))
fi}
assert_equals() {
local expected="$1"
local actual="$2"
local test_name="${3:-Test}"
((TESTS_RUN++))
if [[ "$expected" == "$actual" ]]; then
echo "✓ $test_name" >&2
((TESTS_PASSED++))
else
echo "✗ $test_name" >&2
echo " Expected: $expected" >&2
echo " Actual: $actual" >&2
((TESTS_FAILED++))
fi}
Run tests
Run tests
test_add_numbers() {
local result
result=$(add_numbers 2 3)
assert_equals "5" "$result" "add_numbers 2 3"
}
test_add_numbers
test_add_numbers() {
local result
result=$(add_numbers 2 3)
assert_equals "5" "$result" "add_numbers 2 3"
}
test_add_numbers
Summary
Summary
echo "========================================" >&2
echo "Tests run: $TESTS_RUN" >&2
echo "Passed: $TESTS_PASSED" >&2
echo "Failed: $TESTS_FAILED" >&2
[[ $TESTS_FAILED -eq 0 ]]
undefinedecho "========================================" >&2
echo "Tests run: $TESTS_RUN" >&2
echo "Passed: $TESTS_PASSED" >&2
echo "Failed: $TESTS_FAILED" >&2
[[ $TESTS_FAILED -eq 0 ]]
undefinedShellCheck Integration
ShellCheck集成
bash
#!/usr/bin/env bash
set -euo pipefailbash
#!/usr/bin/env bash
set -euo pipefailValidate script with ShellCheck
Validate script with ShellCheck
validate_script() {
local script="$1"
if ! command -v shellcheck &> /dev/null; then
echo "ShellCheck not installed" >&2
return 1
fi
echo "Running ShellCheck on $script..." >&2
if shellcheck --severity=warning "$script"; then
echo "✓ ShellCheck passed" >&2
return 0
else
echo "✗ ShellCheck failed" >&2
return 1
fi}
validate_script() {
local script="$1"
if ! command -v shellcheck &> /dev/null; then
echo "ShellCheck not installed" >&2
return 1
fi
echo "Running ShellCheck on $script..." >&2
if shellcheck --severity=warning "$script"; then
echo "✓ ShellCheck passed" >&2
return 0
else
echo "✗ ShellCheck failed" >&2
return 1
fi}
Usage
Usage
validate_script myscript.sh
undefinedvalidate_script myscript.sh
undefinedResources
参考资源
Effective debugging requires systematic approaches, comprehensive logging, and proper tooling. Master these techniques for production-ready bash scripts in 2025.
高效的调试需要系统化的方法、全面的日志记录和合适的工具。掌握这些技术,打造2025年生产环境可用的Bash脚本。