Securing AI-Generated Bash Scripts

AI writes Bash easily. It also breaks things easily. A small script can delete your entire home directory if a variable is empty. A simple log script can leak your secrets to a public server.

I have run bad AI scripts. Most engineers have too. Use this checklist to stop disasters before they happen.

Add these lines to the top of every script: #!/usr/bin/env bash set -euo pipefail IFS=$'\n\t'

Why you need them:

  • set -e: Stops the script if any command fails.
  • set -u: Stops the script if a variable is undefined. This prevents rm -rf / errors.
  • set -o pipefail: Ensures errors in a pipeline actually stop the script.
  • IFS=$'\n\t': Prevents bugs caused by spaces in filenames.

Watch for these common AI mistakes:

  1. Missing Quotes AI often writes: rm -rf $TARGET_DIR You must write: rm -rf "$TARGET_DIR" Without quotes, a space in a folder name can delete the wrong files. Always wrap your variables in double quotes.

  2. Secret Leaks AI often uses set -x for debugging. This prints every command to your logs. If you use an API token, that token is now visible in your CI logs. Always remove set -x or use set +x to hide sensitive parts.

  3. Too Much Privilege AI often adds sudo to every command. Do not do this. Run scripts as a non-root user whenever possible. This limits the damage if something goes wrong.

  4. Dangerous Downloads Never run: curl https://example.com/install.sh | bash Instead:

Pro Tip: Use shellcheck. Run shellcheck on every script. It finds unquoted variables and missing safety settings in seconds. It catches what your eyes miss.

The Golden Rule: Treat AI output as a draft. Either include safety requirements in your prompt or harden the code yourself. Do not run AI bash without checking it first.

Source: https://dev.to/devopsaitoolkit/securing-ai-generated-bash-scripts-before-you-run-them-401m

Optional learning community: https://t.me/GyaanSetuAi