Skip to content
nerdsid_
  • Posts
  • Journal

Navigation

  • Posts
  • Journal
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
  • Labs
  • Snippets
  • Quotes
  • Links worth your time
  • About
  • Contact
  • Style guide
  • RSS

© 2026 Sidharth R. · Licensed CC BY-NC-SA 4.0