8.8 KiB
8.8 KiB
AGENTS.md - Agent Coding Guidelines
This document provides guidelines for agents working in this repository.
Project Overview
This is a Bash shell script repository containing multiple independent utilities for Linux server management. Each subdirectory is a separate project.
Subprojects
| Directory | Description |
|---|---|
port-info/ |
Linux port information display (TCP, UDP, HTTP services) |
docker-info/ |
Docker and server information collector |
database-info/ |
Database information collector (WIP) |
systemctl-info/ |
Systemd/systemctl detailed information (v2.0 modular) |
filebrowser/ |
FileBrowser installation/uninstall scripts |
frp/ |
FRP (Fast Reverse Proxy) management scripts |
openlist/ |
OpenList installation/management scripts |
mengyamonitor/ |
MengyanMonitor installation scripts |
user-manager/ |
User management utility |
change-mirror/ |
Mirror changing and Docker installation scripts |
login-info/ |
Login information display |
ssh/ |
SSH key management scripts |
Build / Lint / Test Commands
Running Scripts
# Make executable and run
chmod +x <script>.sh
./<script>.sh
# Or run with bash
bash <script>.sh
Linting
Use shellcheck for static analysis of all Bash scripts:
# Install shellcheck (if not present)
apt-get install shellcheck # Debian/Ubuntu
yum install epel-release && yum install ShellCheck # RHEL/CentOS
# Run shellcheck on a specific script
shellcheck port-info/port_info.sh
shellcheck docker-info/docker-info.sh
# Run with specific severity levels
shellcheck -S error <script>.sh # Errors only
shellcheck -S warning <script>.sh # Warnings and errors
# Check all scripts in repository
shellcheck port-info/*.sh docker-info/*.sh systemctl-info/systemctl-info \
filebrowser/*.sh frp/*.sh openlist/*.sh mengyamonitor/*.sh user-manager/*.sh \
change-mirror/*.sh login-info/*.sh ssh/*.sh
Syntax Validation
# Check bash syntax without executing
bash -n <script>.sh
# Validate all scripts
for f in **/*.sh; do bash -n "$f" && echo "OK: $f"; done
Testing a Single Function
Bash doesn't have traditional unit tests. Test functions interactively:
# Source the script and test specific functions
source <script>.sh
function_name argument # Test specific function
# Example: test port-to-service lookup
source port-info/port_info.sh
get_service_name 80 # Should output: HTTP
Running Full Scripts
# Port info
bash port-info/port_info.sh
# Docker info (requires Docker installed)
bash docker-info/docker-info.sh
# Systemctl info (requires root for full functionality)
sudo bash systemctl-info/systemctl-info
Code Style Guidelines
General Bash Style
Shebang and Error Handling
- Always use
#!/usr/bin/env bashor#!/bin/bash - Add
set -euo pipefailat the start of scripts for safety:-e: Exit on error-u: Exit on undefined variables-o pipefail: Pipeline fails if any command fails
Formatting
- Indentation: 4 spaces (no tabs)
- Line length: Keep lines under 100 characters
- Quotes: Always quote variables:
"$variable"not$variable - Use
printfoverechofor complex output
Naming Conventions
# Functions - snake_case
print_header() { }
get_server_info() { }
check_root() { }
# Variables - descriptive names
local container_output
local cpu_count
local total_mem
# Constants - UPPER_CASE
readonly RED='\033[0;31m'
readonly HEADER_COLOR="${BRIGHT_CYAN}"
Variable Naming Patterns
- Constants (colors, separators): UPPERCASE with underscores, e.g.,
RED,SEPARATOR - Global variables: UPPERCASE, e.g.,
PORT_CMD - Local variables in functions: lowercase with underscores, e.g.,
local port=$1 - Function names: lowercase with underscores, e.g.,
check_commands()
Function Structure
# Good function definition
function_name() {
local arg1=$1
local arg2=$2
# function body
return 0 # Always return explicit status
}
# Document functions with comments
# 获取服务器信息
get_server_info() {
print_header "服务器信息"
local cpu_count=$(grep -c '^processor' /proc/cpuinfo)
print_key_value "CPU核心数" "$cpu_count"
}
Color Variables
Define colors at the top of the script using ANSI escape codes:
# Basic colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color - always reset at end
# Bright colors
BRIGHT_CYAN='\033[1;36m'
BRIGHT_MAGENTA='\033[1;35m'
Error Handling
# Check command existence before use
command_exists() {
command -v "$1" >/dev/null 2>&1
}
if ! command_exists docker; then
print_error "Docker未安装"
exit 1
fi
# Use proper exit codes
if [ "$?" -ne 0 ]; then
echo -e "${RED}Error: command failed${NC}" >&2
exit 1
fi
Input Handling
- Prefer arguments over interactive input
- Validate inputs before processing
- Use
localfor all function parameters - Check for required arguments
String Comparisons
# String equality
if [ "$var" = "value" ]; then
# ...
fi
# Numeric comparison
if [ "$num" -eq 0 ]; then
# ...
fi
# Regex matching
if [[ "$port" =~ ^[0-9]+$ ]]; then
# ...
fi
Common Patterns
Command Availability Check
if command -v ss &> /dev/null; then
PORT_CMD="ss"
elif command -v netstat &> /dev/null; then
PORT_CMD="netstat"
else
echo -e "${RED}Error: ss or netstat not found${NC}"
exit 1
fi
Reading Lines Safely
while IFS= read -r line; do
# process line
done < <(command)
Safe Variable Usage
- Always quote variables:
"$var"not$var - Use
${var}for clarity in complex expressions - Initialize variables before use
Shellcheck Compliance
Run shellcheck and fix all warnings. Common issues:
- SC2086: Quote variables to prevent word splitting
- SC2166: Use
&&instead of-ain test expressions - SC2027: Quote strings containing newlines
- SC2248: Prefer printf over echo
- SC1090: Can't follow non-constant source (use explicit paths)
Output Patterns
Use helper functions for consistent output:
print_header() # Boxed titles
print_section() # Section headers with arrows
print_key_value() # Key: Value pairs
print_success() # Green checkmark
print_warning() # Yellow warning
print_error() # Red X
Testing Checklist
Before submitting changes:
- Run
shellcheck <script>.shwith no warnings - Run
bash -n <script>.shfor syntax check - Test on a system with required dependencies
- Test on a system without optional dependencies (graceful degradation)
- Verify all color output displays correctly
- Check that tables align properly
Documentation
- Use Chinese comments to match existing codebase style (most scripts are Chinese-language)
- Add section separators:
#=============================================================================== - Document function purpose before definition
- Include usage information in comments
- Document dependencies clearly
File Extensions
- Bash scripts:
.sh - Executable scripts may have no extension
- Service files:
.service
Subproject Guidelines
For specific subproject guidelines, see the AGENTS.md files in each subdirectory:
Dependencies
Required (Common)
bash(4.0+)- Standard POSIX utilities:
awk,grep,sed,sort,uniq
Optional
docker- for docker-info scriptsystemctl,journalctl- for systemctl-info scriptshellcheck- for lintingjq- for better JSON parsing
Security Notes
- Some scripts require root/sudo for full functionality
- Always validate user input if adding new features
- Use proper quoting to prevent word splitting and globbing
- Sanitize any data passed to
evalor similar dangerous operations - Never hardcode credentials or sensitive data
Common Tasks
Adding a New Port Service (port-info)
Edit get_service_name() function:
get_service_name() {
local port=$1
case $port in
80) echo "HTTP" ;;
443) echo "HTTPS" ;;
3306) echo "MySQL" ;;
9000) echo "PHP-FPM" ;;
*) echo "未知" ;;
esac
}
Adding a New Module (systemctl-info)
- Create a new function following existing patterns:
module_xxx() - Add function to the module list array
- Use consistent color scheme and formatting
- Add documentation in the AGENTS.md
Adding a New Utility
- Create new directory if it's a significant project
- Follow the code style guidelines above
- Create an AGENTS.md for the subproject
- Add to the project table in this file