Yeda AI Tips · #133

Español

Never Build Shell Commands As Strings

You're one unquoted variable away from deleting the wrong directory. When your AI agent — or your own script — glues a command together as a string, the shell gets a second vote on what that string means. A stray space, an empty variable, or a filename with a glob character, and it runs something you never wrote.

Why strings split apart

The shell does not run the string you typed. It runs the string after word splitting and pathname expansion. Both happen on every unquoted expansion.

DIR="my project"
rm -rf $DIR        # runs: rm -rf my project   → two arguments
rm -rf "$DIR"      # runs: rm -rf 'my project' → one argument

Worse, if $DIR is empty or unset, rm -rf $DIR/ becomes rm -rf /. The command looks correct in your editor and is catastrophic at runtime. This is Bash Pitfall #1 and #2: the results of an expansion are still subject to word splitting and pathname expansion, so you always double-quote parameter expansions.

The three habits

HabitInstead ofDo this
Argument listscmd="rm -rf $files"; $cmdargs=(-rf "$file"); rm "${args[@]}"
Every expansiongrep $pat $filegrep "$pat" "$file"
Fail fast(no guard)set -euo pipefail

Use arrays for argument lists. A Bash array keeps each element a distinct word regardless of spaces or empty values. "${args[@]}" expands to exactly the elements you put in — no re-splitting, no globbing:

flags=(--exclude "*.log" --exclude "tmp dir")
rsync "${flags[@]}" "$src" "$dst"

Quote every expansion by default. "$var", "${arr[@]}", "$(cmd)". The rare case where you want splitting is the exception you comment; quoting is the default you never think about.

Fail fast, don't destroy state silently

Start scripts with the strict trio:

set -euo pipefail

Together they turn silent, half-finished damage into a loud, early exit. set -u alone would have caught the empty-$DIR disaster above.

Power user notes

Never construct commands in strings. Build argument lists as arrays, quote everything, and let the script fail loudly the instant something is off.

Resources

Shipping scripts that AI agents write and run? Yeda AI audits and hardens the automation in your stack.

Talk to us · More AI-coding tips