Przejdลบ do treล›ci

๐Ÿง  AI Shell: Prompt Engineering

Large Language Models (LLMs) like GPT-4, Claude, and Llama are incredibly powerful at writing shell scripts, but they often default to lazy, non-portable, or unsafe code. Mastering prompt engineering for shell scripting is about forcing the AI into a strict, disciplined engineering mindset.


๐ŸŽฏ The "Context Framing" Principle

When asking an LLM to write a shell script, you must provide explicit boundaries. Without boundaries, the AI will likely generate a mix of Bashisms, ignore error handling, and forget about cross-platform compatibility.

โŒ The Bad Prompt (Lazy)

"Write a script to backup my database and send it to S3."

Result: The AI will likely write a script without set -e, hardcode credentials, use non-portable date flags, and ignore logging.

โœ… The Good Prompt (Engineered)

"Write a shell script to backup a PostgreSQL database and upload it to AWS S3.

Constraints: - Must be strict POSIX sh (no bashisms). - Must use set -euo pipefail. - Must use standard tools only (pg_dump, gzip, aws cli). - Must implement structured logging (JSON or timestamped). - Do NOT hardcode credentials; read them from environment variables with safe defaults. - Ensure idempotency: do not fail if the backup directory already exists."


๐Ÿ“‹ The "System Prompt" for Shell Generation

If you use tools like GitHub Copilot, Cursor, or a custom AI CLI, you can set a System Prompt. This acts as the universal law for the AI.

Use this battle-tested system prompt for world-class shell generation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
You are an expert DevOps Engineer and Unix/Linux System Administrator.
When generating shell scripts, you MUST adhere to the following rules:

1. COMPATIBILITY: Default to POSIX sh unless Bash is explicitly requested. If Bash is requested, use `#!/usr/bin/env bash`.
2. SAFETY: Always start scripts with `set -euo pipefail`.
3. CLEAN CODE: Use clear variable names. Prefix private variables with `_`. Use `local` (or equivalent) in functions.
4. ERROR HANDLING: Check the existence of required CLI tools before using them. Return meaningful exit codes.
5. NO HALLUCINATIONS: Do not invent flags for commands. If a command behaves differently on GNU vs BSD (e.g., `sed`, `date`, `find`), write portable code or explicitly state the assumption.
6. SECURITY: Never hardcode secrets. Do not use `eval` unless absolutely necessary.
7. IDEMPOTENCY: Ensure file/directory creation and state changes are idempotent.

๐Ÿ”„ Iterative Refinement Patterns

AI rarely writes a perfect 200-line script on the first try. Use the Iterative Refinement pattern to build complex scripts safely.

Step 1: Core Logic

"Write just the core pg_dump and gzip function. Do not include error handling yet."

Step 2: Error Handling

"Now, wrap this function in a retry mechanism with exponential backoff. Max retries: 3."

Step 3: Argument Parsing

"Add a POSIX-compliant getopts loop to parse --host, --user, and --bucket."

Step 4: Security Review

"Review the script above for security vulnerabilities, specifically command injection via the --user argument."


๐ŸŽญ Few-Shot Prompting for Shell Style

LLMs mimic the style you provide. If you want a script written in the Library-Style Shell pattern (see 50-patterns), provide a "Few-Shot" example.

Prompt:

"I want you to write a network health check function. It must follow the exact style and error handling pattern as this example:"

1
2
3
4
5
6
7
8
9
# Example format:
fs_ensure_dir() {
    local dir="$1"
    if [ -z "$dir" ]; then
        log_error "Directory path required"
        return 1
    fi
    mkdir -p "$dir" || return 1
}
"Now, write net_check_port(). It should take a host and a port, and use nc to check if it's open."


๐Ÿ› ๏ธ Contextual Injection via CLI

When using CLI-based AI tools (like sgpt or gh copilot), inject your environment context directly into the prompt using command substitution.

1
2
3
# Injecting the OS and tool version context to avoid GNU/BSD flag hallucinations
ai "Write a command to find files older than 30 days and delete them.
    Context: OS is $(uname -s), find version is $(find --version 2>&1 | head -n1)"

๐Ÿงพ Summary Checklist

โœ… Define the Interpreter: Always specify POSIX sh vs bash vs zsh. โœ… Demand Strict Mode: Explicitly ask for set -euo pipefail. โœ… Specify the OS: Tell the AI if this is for Linux (GNU tools), macOS (BSD tools), or Alpine (BusyBox). โœ… Provide Style Guides: Use few-shot examples to enforce your logging and error-handling standards. โœ… Ban Bad Practices: Explicitly forbid eval, hardcoded secrets, and parsing ls output.


๐Ÿงพ See Also