Sidharth R
  • Home
  • Posts
  • Journal
  • Home
  • Posts
  • Journal
  • Search
Posts

Using Shell Variables to Avoid Errors

Updated: 12 Aug 2026

Task

Create two files (release.txt, owner.txt) under a directory release-packages/northwind-api. The goal is to avoid typos by storing the path once in a variable.

Approach

Store the repeated path in a shell variable (TARGET_DIR), then reference it for both directory creation and file writes.

Solution

file.sh
#!/bin/bash
set -euo pipefail
TARGET_DIR=release-packages/northwind-api
mkdir -p "$TARGET_DIR"
echo 'release=2026.06.09' > "$TARGET_DIR/release.txt"
echo 'owner=platform' > "$TARGET_DIR/owner.txt"

Now run the script using chmod +x file.sh, then ./file.sh.

Verification

Cat file contents
$ cat release-packages/northwind-api/release.txt 
release=2026.06.09
$ cat release-packages/northwind-api/owner.txt
owner=platform

Verification isn’t just a formality. For example, a typo in the path or quoting can fail silently (e.g. create a wrongly named file) instead of throwing an error. So always confirm output rather than trusting the script ran correctly.

Gotchas & Best Practices

Quoting matters for variable substitution

  • Double quotes "$TARGET_DIR/release.txt" → shell expands the variable correctly.
  • Single quotes '$TARGET_DIR/release.txt' → no expansion happens; the literal string $TARGET_DIR is used instead, breaking the script.
Memo

Memo: single quotes = literal string, double quotes = allows variable/command substitution.

echo and redirection

  • > overwrites the file each run; >> would append instead.
  • echo adds a trailing newline. If exact byte content (no newline) is required, use printf '%s' 'text' > file instead.

Variable naming

  • All-caps names like TARGET_DIR are a common shell convention for script-level variables. But avoid names that collide with real env vars (e.g. PATH, HOME).

Script safety

  • Adding set -euo pipefail at the top makes the script exit on errors, undefined variables, or failed pipe commands instead of silently continuing.
Tags: linux bash shell-scripting cli … views

Keep reading

  • Practical Grep: Filtering Errors and Patterns in Log Files
  • Linux Commands Cheat Sheet (Most Used Commands)
  • Grep Failing on Hyphen Patterns? Try This Fix
  • 4 Ways to Watch Logs Live in Linux

  • Home
  • Posts
  • Journal
  • Quotes
  • Links worth your time
  • About
  • Contact
  • Style guide
  • RSS
© 2026 Sidharth R.
Licensed CC BY-NC-SA 4.0