iToverDose/Software· 18 JUNE 2026 · 16:05

Five critical checks to run AI-generated bash scripts safely

AI can write dangerous Bash scripts in seconds—here’s a simple checklist to avoid data loss, secret leaks, and execution failures before you press Enter.

DEV Community4 min read0 Comments

AI tools make writing Bash scripts effortless, but they also make it easy to create scripts that delete files, expose credentials, or crash mid-execution. A seemingly harmless one-liner can wipe a home directory when a variable isn’t set. A log-shipping tool might quietly send your API keys to a third party. These risks aren’t hypothetical—engineers have experienced them firsthand.

Before you run any AI-generated Bash script, apply this quick checklist. It takes minutes but can prevent irreversible damage.

Start with the strictest safety pragma

Every non-trivial Bash script should begin with a strict pragma that enforces safety and predictability. Add these lines to the top of the script:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

Here’s what each setting does:

  • set -e forces the script to exit immediately if any command fails. Without it, a failure on line 5 won’t stop the script from continuing to line 50.
  • set -u raises an error if the script references an undefined variable. This prevents rm -rf $UNDEFINED/ from becoming rm -rf / when $UNDEFINED is empty.
  • set -o pipefail ensures that pipelines fail if any command in the pipeline fails. Without it, failing-command | grep something might succeed because grep succeeds even if failing-command didn’t.
  • IFS=$'\n\t' sets a safer field separator, reducing risks from word-splitting bugs in filenames.

If the AI-generated script lacks these lines, add them and re-review the script. You’ll often catch subtle bugs that the pragma now flags.

Quote every variable expansion — no exceptions

Unquoted variables are the most common cause of Bash disasters. Consider this example:

# Unsafe
rm -rf $TARGET_DIR

# Safe
rm -rf "$TARGET_DIR"

If $TARGET_DIR is empty or contains spaces, the unsafe version becomes rm -rf (deleting the current directory) or rm -rf foo bar (deleting multiple unintended targets). AI models often default to the unsafe version because it’s easier to write in chat and more common in blog tutorials.

Rule of thumb: Treat every $VAR like a ticking bomb. Add quotes around it. This single habit prevents the majority of Bash-related catastrophes.

Plan for failure at every step

AI scripts frequently assume every command will succeed. Reality is different. Review each step for recovery paths:

mkdir -p /opt/new-app
cd /opt/new-app
tar xzf $TARBALL
rm $TARBALL

What happens if tar xzf fails? With set -e, the script stops. Without it, the script proceeds to rm $TARBALL, deleting the tarball without a backup. For state-changing scripts, ask: What if this step fails? If the answer is nothing automated, the script should at least avoid deleting data before verifying prior steps succeeded.

AI almost never considers failure recovery on its own. Manual review is essential.

Hide secrets from logs and traces

Debugging tools like set -x can leak sensitive information. Consider this example:

set -x
curl -H "Authorization: Bearer $API_TOKEN" 

With set -x enabled, the terminal prints every command, including expanded variables. Your API token ends up in CI logs, visible to anyone with project access. To prevent this, disable tracing before sensitive commands:

set +x
curl -H "Authorization: Bearer $API_TOKEN" 
set -x

Alternatively, remove set -x entirely after debugging. AI models often leave it in by default, creating hidden exposure risks.

Avoid running as root unless absolutely necessary

AI scripts sometimes sprinkle sudo across every command or assume root privileges. Excessive privilege escalation increases the blast radius of any mistake. Follow the principle: Run with the least privileges possible.

Compare these two patterns for downloading and executing a script:

# Dangerous — runs everything as root
sudo bash -c 'curl  | bash'

# Safer — review before execution
curl  > install.sh
# Read install.sh
sudo bash install.sh

If the AI-generated script uses the first pattern, replace it with the second. Always review scripts before granting elevated permissions.

Real-world example: cleaning up Docker images

A recent request to an AI assistant asked for a script to delete Docker images older than 30 days. The first draft looked like this:

#!/bin/bash
DOCKER_IMAGES=$(docker images --format '{{.ID}} {{.CreatedAt}}')
CUTOFF=$(date -d '30 days ago' +%s)
echo "$DOCKER_IMAGES" | while read ID DATE; do
  CREATED=$(date -d "$DATE" +%s)
  if [ $CREATED -lt $CUTOFF ]; then
    docker rmi $ID
  fi
done

Applying the checklist revealed several issues:

  • Missing strict pragma (set -euo pipefail).
  • Unquoted variables ($DOCKER_IMAGES, $ID, $DATE).
  • No handling for docker rmi failures (e.g., images in use).
  • No audit trail for what was removed or skipped.
  • No sudo usage, which was appropriate given Docker socket access.

The hardened version fixed these issues:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

CUTOFF=$(date -d '30 days ago' +%s)
REMOVED=0
SKIPPED=0

docker images --format '{{.ID}}|{{.CreatedAt}}' | while IFS='|' read -r ID DATE; do
  CREATED=$(date -d "$DATE" +%s)
  if [ "$CREATED" -lt "$CUTOFF" ]; then
    if docker rmi "$ID" 2>/dev/null; then
      echo "Removed: $ID"
      REMOVED=$((REMOVED + 1))
    else
      echo "Skipped (in use): $ID"
      SKIPPED=$((SKIPPED + 1))
    fi
  fi
done

echo "Cleanup complete. Removed: $REMOVED, Skipped: $SKIPPED."

This version added strict safety, quoted variables, failure handling, and audit logging. The edits took less than two minutes, preventing a scenario where the script appeared to run successfully but didn’t actually reduce disk usage due to in-use images.

Automate safety with shellcheck

While manual review is essential, automation speeds up the process. The tool shellcheck flags most common Bash issues automatically:

shellcheck cleanup-images.sh

It highlights unquoted variables, missing pragmas, and unsafe constructs. If you adopt only one tool from this article, make it shellcheck.

The bottom line: treat AI-generated Bash like untrusted code

AI accelerates scripting but doesn’t eliminate risk. A few minutes of review can mean the difference between a harmless cleanup script and a data disaster. Use the checklist consistently, automate what you can, and always remember: Bash scripts are powerful, and so are the consequences of mistakes.

AI summary

AI writes Bash scripts fast—but they can wipe disks or leak secrets. Use this 5-step checklist to vet AI-generated Bash before running it and avoid catastrophic mistakes.

Comments

00
LEAVE A COMMENT
ID #XWEH6O

0 / 1200 CHARACTERS

Human check

2 + 4 = ?

Will appear after editor review

Moderation · Spam protection active

No approved comments yet. Be first.