4.6a Variables, quoting rules, and command substitution ($())

📦 Operating System Layer 📖 Core Linux Administration for AI Operators

🌱 Context Introduction

When automating AI infrastructure tasks — such as spinning up GPU nodes, managing storage volumes, or scheduling model training jobs — you will constantly work with variables, quoting rules, and command substitution in Bash scripts. These three concepts form the foundation of writing reliable, repeatable automation scripts. Understanding them helps you avoid common pitfalls like missing file paths, broken variable expansions, or incorrect command outputs.

⚙️ Variables in Bash

Variables store data that your script can reference and manipulate. Think of them as labeled containers for values like server names, file paths, or GPU counts.

🔑 Key Points

  • Variable assignment uses the format: variable_name=value (no spaces around the equals sign)
  • Variable access uses the dollar sign: $variable_name or ${variable_name}
  • Variable names are case-sensitive and typically use uppercase for constants, lowercase for temporary values
  • Use curly braces ${} to clearly separate the variable name from surrounding text

📝 Example Scenario

For reference:

server_name="gpu-node-01"
gpu_count=8
echo "The server $server_name has ${gpu_count} GPUs"

📤 Output: The server gpu-node-01 has 8 GPUs


🛡️ Quoting Rules

Quoting controls how Bash interprets special characters like spaces, dollar signs, and backslashes. There are three types of quotes, each with a different behavior.

📊 Comparison Table: Quote Types

Quote Type Symbol Behavior Use Case
Double quotes " " Preserves spaces, but allows variable expansion and command substitution When you want to use variables inside a string
Single quotes ' ' Preserves everything literally — no expansion or substitution When you need exact text, like passwords or paths with special characters
Backslash **\ ** Escapes the next character only When you need to escape a single special character

🧪 Practical Examples

For reference:

model_name="Llama 3"
echo "Model: $model_name"
echo 'Model: $model_name'
echo "Path: /home/user/my models"
echo "Path: /home/user/my\ models"

📤 Output: - Model: Llama 3 - Model: $model_name - Path: /home/user/my models - Path: /home/user/my models


🔄 Command Substitution ($())

Command substitution allows you to capture the output of a command and store it in a variable or use it directly in your script. This is essential for dynamic automation — for example, getting the current GPU temperature or checking available disk space.

🛠️ Two Syntax Forms

  • $() — modern, nestable, and preferred
  • `` (backticks) — older syntax, harder to read and nest

🧠 How It Works

The command inside $() runs first, and its output replaces the entire $() expression. This output can then be assigned to a variable or used inline.

📝 Example Scenario

For reference:

current_date=$(date +%Y-%m-%d)
gpu_count=$(nvidia-smi --query-gpu=count --format=csv,noheader)
echo "Backup date: $current_date"
echo "Number of GPUs: $gpu_count"

📤 Output: - Backup date: 2025-04-10 - Number of GPUs: 8


🕵️ Common Pitfalls and Best Practices

❌ Mistakes to Avoid

  • Forgetting quotes around variable values that contain spaces — leads to word splitting and broken commands
  • Using single quotes when you need variable expansion — the variable name will be treated as literal text
  • Nesting backticks without escaping — causes syntax errors; always use $() for nesting
  • Not using curly braces when variables are adjacent to other characters — Bash may misinterpret the variable name

✅ Best Practices

  • Always double-quote variable expansions: "$variable" to preserve spaces and special characters
  • Use $() instead of backticks for command substitution — it is cleaner and supports nesting
  • Test quoting behavior with echo before running critical commands
  • Use set -u at the top of scripts to catch unset variables early

🧩 Putting It All Together

A typical AI infrastructure automation script might combine all three concepts:

For reference:

#!/bin/bash
set -u

log_dir="/var/log/ai-jobs"
job_name="training-run-$(date +%s)"
gpu_available=$(nvidia-smi --query-gpu=index --format=csv,noheader | wc -l)

echo "Job: $job_name"
echo "Log path: ${log_dir}/${job_name}.log"
echo "Available GPUs: $gpu_available"

📤 Output: - Job: training-run-1744320000 - Log path: /var/log/ai-jobs/training-run-1744320000.log - Available GPUs: 8

📊 Visual Representation: Bash Parser Quoting Evaluation

This flowchart shows how the Bash parser processes string inputs differently based on whether they are enclosed in single quotes, double quotes, or command substitution blocks.

flowchart LR eval["Bash Parser evaluates input"] eval --> single["Single Quotes"] eval --> double["Double Quotes"] eval --> sub["Command Sub: $()"] single -->|Process| lit["Literal string (No expansion)<br>'$VAR' -> '$VAR'"] double -->|Process| exp["Expand variables & command sub<br>'$VAR' -> value"] sub -->|Process| exec["Execute command & return stdout<br>'$(date)' -> Sun Jun 28"] classDef cpu fill:#eafaf1,stroke:#76b900,stroke-width:2px,rx:6px,ry:6px; classDef memory fill:#f0f7ff,stroke:#3498db,stroke-width:1.5px,rx:4px,ry:4px; classDef system fill:#f1f5f9,stroke:#64748b,stroke-width:1.5px; class sub,exec cpu; class double,exp memory; class eval,single,lit system;

📚 Summary

  • Variables store and reuse values in your scripts
  • Quoting rules control how Bash interprets special characters — use double quotes for expansion, single quotes for literals
  • Command substitution ($()) captures command output for dynamic automation
  • Combining these three concepts correctly is essential for writing robust, error-free Bash scripts for AI infrastructure operations

Next topic: 4.6b Conditional statements (if, case) and loops (for, while)