Linux Scripting Best Practices
This article was last updated on: May 17, 2026 am
Preface
You can feed this article directly to an AI, add it to an AI role definition, or use it directly as a prompt.
That way, you just describe the requirements and let the AI write the scripts.
I. Fundamental Principles
-
Clarify the Purpose
-
Use comments at the beginning of the script to describe its function, author, version, and change history
-
Example:
1
2
3
4#!/bin/bash
# Purpose: Backup MySQL databases
# Author: John Doe
# Version: 1.2 (2023-08-20)
-
-
Choose the Right Interpreter
-
Explicitly specify the interpreter (avoid relying on the default shell):
1
2
3#!/usr/bin/env bash # Recommended (better portability)
# or
#!/bin/bash # Explicit version
-
II. Code Standards
-
Variable Management
-
Use uppercase with underscores for naming; use lowercase for local variables
1
2readonly CONFIG_FILE="/etc/app.conf"
local temp_file="$(mktemp)" -
Quote variables with double quotes (to prevent issues with spaces/special characters):
1
cp "$source" "$dest"
-
-
Error Handling
-
Enable strict mode (add at the beginning of the script):
1
set -euo pipefail # -e: exit on error -u: error on undefined variables -o pipefail: detect pipe failures -
Check return values for critical operations:
1
2
3
4if ! mkdir "/backup"; then
echo "Failed to create directory" >&2
exit 1
fi
-
-
Function Usage
-
Modularize functionality and limit function scope:
1
2
3
4process_data() {
local input_file=$1
# Function logic...
}
-
III. Security
-
Input Validation
-
Validate user input/arguments:
1
2
3
4if [[ $# -lt 2 ]]; then
echo "Usage: $0 <source> <dest>" >&2
exit 1
fi
-
-
Permission Control
-
Avoid running non-essential operations as root:
1
2
3
4if [[ $(id -u) -ne 0 ]]; then
echo "Requires root privileges" >&2
exit 1
fi
-
-
Sensitive Information
- Never hardcode passwords/keys; use environment variables or configuration files (with permissions set to 600)
IV. Maintainability
-
Logging
-
Log important operations:
1
2
3
4log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "/var/log/script.log"
}
log "Starting backup process..."
-
-
Separate Configuration Files
-
Extract configuration parameters into a separate file (e.g., config.cfg):
1
source ./config.cfg || exit 1
-
V. Debugging and Testing
-
Debug Mode
-
Display command execution at runtime:
1
2
3bash -x script.sh
# Or enable within the script
set -x
-
-
Unit Testing
- Write test cases for critical functions (you can use the bats framework)
VI. Performance Optimization
-
Reduce subprocess calls (e.g., avoid calling grep/awk inside loops)
-
Use built-in string operations instead of external commands:
1
2# Instead of: echo "$str" | cut -d':' -f2
echo "${str#*:}" -
Use stream processing for large files (avoid loading entire files into memory)
Template Example
1 | |