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

  1. 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)
  2. 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

  1. Variable Management

    • Use uppercase with underscores for naming; use lowercase for local variables

      1
      2
      readonly 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"
  2. 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
      4
      if ! mkdir "/backup"; then
      echo "Failed to create directory" >&2
      exit 1
      fi
  3. Function Usage

    • Modularize functionality and limit function scope:

      1
      2
      3
      4
      process_data() {
      local input_file=$1
      # Function logic...
      }

III. Security

  1. Input Validation

    • Validate user input/arguments:

      1
      2
      3
      4
      if [[ $# -lt 2 ]]; then
      echo "Usage: $0 <source> <dest>" >&2
      exit 1
      fi
  2. Permission Control

    • Avoid running non-essential operations as root:

      1
      2
      3
      4
      if [[ $(id -u) -ne 0 ]]; then
      echo "Requires root privileges" >&2
      exit 1
      fi
  3. Sensitive Information

    • Never hardcode passwords/keys; use environment variables or configuration files (with permissions set to 600)

IV. Maintainability

  1. Logging

    • Log important operations:

      1
      2
      3
      4
      log() {
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "/var/log/script.log"
      }
      log "Starting backup process..."
  2. Separate Configuration Files

    • Extract configuration parameters into a separate file (e.g., config.cfg):

      1
      source ./config.cfg || exit 1

V. Debugging and Testing

  1. Debug Mode

    • Display command execution at runtime:

      1
      2
      3
      bash -x script.sh
      # Or enable within the script
      set -x
  2. Unit Testing

    • Write test cases for critical functions (you can use the bats framework)

VI. Performance Optimization

  1. Reduce subprocess calls (e.g., avoid calling grep/awk inside loops)

  2. Use built-in string operations instead of external commands:

    1
    2
    # Instead of: echo "$str" | cut -d':' -f2
    echo "${str#*:}"
  3. Use stream processing for large files (avoid loading entire files into memory)

Template Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# !/usr/bin/env bash
set -euo pipefail

# --- Configuration ---
readonly LOCK_FILE="/var/lock/script.lock"
readonly LOG_FILE="/var/log/script.log"

# --- Functions ---
init() {
if [ -f "$LOCK_FILE" ]; then
log "Error: Script is already running"
exit 1
fi
touch "$LOCK_FILE"
}

cleanup() {
rm -f "$LOCK_FILE"
log "Script completed"
}

log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}

# --- Main Logic ---
main() {
init
trap cleanup EXIT # Ensure cleanup on exit

# Business logic...
log "Processing started"
}

main "$@"

Linux Scripting Best Practices
https://e-whisper.com/posts/48106/
Author
east4ming
Posted on
July 12, 2025
Licensed under