Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Write Bash/PowerShell Scripts Using AI

Use an AI assistant to write shell scripts you can trust: clear flags, safe defaults, and a quick dry run before anything destructive.

In short: say Bash or PowerShell, describe inputs and the exact success message, forbid silent deletes, then run the script on a throwaway folder first.

Why shell scripts with AI

WHY

Every developer and DevOps engineer automates backups, log checks and deploys with Bash (Linux/Mac) or PowerShell (Windows, and now Linux too). AI writes the loop fast. One wrong rm can delete a day of work.

What you need

WHAT
  • Bash: default on Linux and Mac. Check: bash --version.
  • PowerShell 7+: on Windows (and installable on Linux/Mac). Check: pwsh --version.
  • An editor + assistant: VS Code + Copilot or Claude Code works for both.
  • A scratch folder: never test a new script on production data first.

How it flows

1 · Say Bash or PowerShell inputs + output text 2 · Ask for safe flags set -euo pipefail / Stop on error 3 · AI writes the script read every line 4 · Dry-run on a temp folder check the message 5 · Then use on real paths still no blind rm

Step 1 — Bash prompt

COPY THIS PROMPT (BASH)

Write a Bash script backup_folder.sh that takes one argument (a folder path). If missing or not a directory, print Usage on stderr and exit 1. Copy the folder to $HOME/backups/<name>-YYYYMMDD-HHMMSS with cp -a. Use set -euo pipefail. Print the destination path. Only return the script.

Step 2 — Bash script (tested here)

backup_folder.sh
#!/usr/bin/env bash
# backup_folder.sh — copy a folder into ~/backups/<name>-YYYYMMDD-HHMMSS
set -euo pipefail

SRC="${1:-}"
if [[ -z "$SRC" || ! -d "$SRC" ]]; then
  echo "Usage: $0 /path/to/folder" >&2
  exit 1
fi

NAME="$(basename "$SRC")"
STAMP="$(date +%Y%m%d-%H%M%S)"
DEST="${HOME}/backups/${NAME}-${STAMP}"
mkdir -p "$(dirname "$DEST")"
cp -a "$SRC" "$DEST"
echo "Backed up to $DEST"
chmod +x backup_folder.sh
TMP=$(mktemp -d); echo hi > "$TMP/a.txt"
./backup_folder.sh "$TMP"
# -> Backed up to /home/…/backups/…-YYYYMMDD-HHMMSS

Step 3 — same idea in PowerShell

COPY THIS PROMPT (POWERSHELL)

Write Backup-Folder.ps1 with a mandatory -Path folder parameter. Validate the folder exists. Copy it recursively to $HOME/backups/<name>-yyyyMMdd-HHmmss. Print the destination. Stop on errors.

Backup-Folder.ps1
# Backup-Folder.ps1 — copy a folder into ~/backups/<name>-yyyyMMdd-HHmmss
param(
  [Parameter(Mandatory = $true)]
  [string]$Path
)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
  Write-Error "Folder not found: $Path"
  exit 1
}
$name = Split-Path -Leaf $Path
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$dest = Join-Path $HOME "backups/${name}-${stamp}"
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -LiteralPath $Path -Destination $dest -Recurse
Write-Host "Backed up to $dest"
pwsh -File Backup-Folder.ps1 -Path .\my-folder
# -> Backed up to …\backups\my-folder-…

Settings and safe habits

  1. Rules file: “Bash: set -euo pipefail; PowerShell: $ErrorActionPreference = 'Stop'; never rm -rf without an explicit dry-run flag”.
  2. Ask the AI to add a --dry-run flag for any script that deletes or overwrites.
  3. Quote every variable: "$SRC", not bare $SRC (spaces in paths).
  4. Prefer cp -a / Copy-Item over hand-rolled loops for simple backups.

Watch out (common AI mistakes in shell)

  • Unquoted variables — break on spaces; always quote.
  • Missing set -e — script continues after a failed command.
  • rm -rf $VAR when VAR is empty — can target the wrong path; check emptiness first.
  • curl | bash from the internet — do not auto-approve.
  • PowerShell vs cmd.exe — say pwsh / PowerShell 7 in the prompt so you do not get old Windows cmd syntax.
Rule: never let an agent run a generated script with delete or overwrite powers on your real home folder until you have tested it on a temp folder.

Try this yourself: ask AI for a Bash extension counter, then prove the cases

Hello friends. The live chapter already walked through a backup_folder.sh helper. This practice is a different fictional lab called Copper Lantern Labs. You ask an AI for a Bash script count_ext.sh that counts files with one extension inside one directory (non-recursive), prints COUNT equals the number, and prints Usage on stderr with exit 1 for bad arguments. A PowerShell twin Count-Ext.ps1 is included as teaching text for Windows students. On this drafting Linux machine we ran the Bash script for real with /usr/bin/bash under a pytest harness: the starter failed all 7 tests, and the fixed script passed all 7. There is no pwsh here, so PowerShell was not executed.

Ravindra Bagale's Tip

Put COUNT equals n, non-recursive matching, and Usage on stderr with exit 1 in your prompt. Keep set -euo pipefail near the top of the Bash script, and keep the PowerShell twin for Windows even when you prove Bash first.

Practice label: Copper Lantern Labs, every path and every file count here is fictional teaching data. It is not a real laboratory. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box ran the Bash scripts with /usr/bin/bash 5.2.37 under Python 3.13.5 and pytest 9.1.1. Starter Bash: 7 failed. Fixed Bash: 7 passed. pwsh was not installed and PowerShell was not run. The Count-Ext.ps1 files remain student-facing teaching twins for Windows.

Your task: start from the buggy count_ext.sh that prints a bare number, walks nested folders, and weak-checks arguments. Ask an AI to print COUNT=<n>, count only direct children, accept txt or .txt, print Usage on stderr with exit 1 for bad args, and keep a matching PowerShell twin for Windows.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Save count_ext.sh and make it executable with chmod +x count_ext.sh.
  3. Optional harness: copy test_count_ext.py beside the script and run python3 -m pytest -q test_count_ext.py (needs pytest).
  4. On Windows: keep Count-Ext.ps1 for PowerShell; this drafting box could not run pwsh.

Starter count_ext.sh (recursive, bare number, weak args):

count_ext.sh
#!/usr/bin/env bash
# Copper Lantern Labs extension counter (fictional teaching lab — not a real company).
# Starter: weak args, wrong COUNT format, and counts recursively.
set -euo pipefail

if [[ $# -lt 1 ]]; then
  echo "need args" >&2
  exit 1
fi

DIR="${1:-.}"
EXT="${2:-txt}"

# Starter bugs: recursive find; prints bare number instead of COUNT=<n>;
# does not require exactly 2 args; does not strip a leading dot from EXT.
n=$(find "$DIR" -type f -name "*.${EXT}" 2>/dev/null | wc -l | tr -d ' ')
echo "$n"

Starter PowerShell twin (teaching text only on this box):

Count-Ext.ps1
# Copper Lantern Labs extension counter (fictional teaching lab — not a real company).
# Starter PowerShell twin: weak args, recursive Get-ChildItem, bare number output.
param(
    [string]$Directory = ".",
    [string]$Extension = "txt"
)

if (-not $Directory) {
    Write-Error "need args"
    exit 1
}

$files = Get-ChildItem -Path $Directory -Filter "*.$Extension" -Recurse -File -ErrorAction SilentlyContinue
Write-Output $files.Count

Suggested AI ask (copy and adapt):

bash-prompt.txt
Write a Bash script count_ext.sh for fictional Copper Lantern Labs. Take exactly two arguments: a directory and an extension (txt or .txt). Count only direct files in that directory matching *.<ext> (non-recursive). Print COUNT=<n> on stdout. On wrong arity, empty args, or missing directory, print a Usage line on stderr and exit 1. Use set -euo pipefail. Also draft a matching PowerShell Count-Ext.ps1 with the same behavior for Windows students.

HOW to finish

HOW
  1. Save the starter Bash script and make it executable.
  2. Ask your AI assistant to print COUNT equals n, stay non-recursive, strip a leading dot from the extension, and print Usage on stderr with exit 1 for bad args.
  3. Run the harness (or manual fixtures). On this drafting box the starter showed 7 failed.
  4. Run again after the fix. Expect 7 passed. Keep the PowerShell twin for your Windows machine; pwsh was not run here.

Real pytest harness output after the fixed Bash script:

pytest-after.txt
.......                                                                  [100%]
7 passed in 0.02s
Optional completed count_ext.sh (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if the harness cases all pass.

count_ext.sh
#!/usr/bin/env bash
# Copper Lantern Labs extension counter (fictional teaching lab — not a real company).
set -euo pipefail

usage() {
  echo "Usage: count_ext.sh <directory> <extension>" >&2
  echo "Example: count_ext.sh ./samples txt" >&2
}

if [[ $# -ne 2 ]]; then
  usage
  exit 1
fi

DIR="$1"
EXT="$2"

if [[ -z "$DIR" || -z "$EXT" ]]; then
  usage
  exit 1
fi

EXT="${EXT#.}"

if [[ ! -d "$DIR" ]]; then
  echo "Usage: count_ext.sh <directory> <extension>" >&2
  echo "error: directory not found: $DIR" >&2
  exit 1
fi

n=0
shopt -s nullglob
for f in "$DIR"/*."$EXT"; do
  if [[ -f "$f" ]]; then
    n=$((n + 1))
  fi
done
shopt -u nullglob

echo "COUNT=${n}"

Troubleshooting

HOW
  1. Problem: the script prints 3 when a nested deep.txt exists beside two top-level txt files. Fix: count only direct children, not recursive find.
  2. Problem: the script prints 2 instead of COUNT=2. Fix: print the exact COUNT= prefix the tests expect.
  3. Problem: passing .txt counts zero files. Fix: strip a leading dot from the extension before matching.
  4. Error: pwsh is missing on the drafting box. Fix: prove Bash here; keep Count-Ext.ps1 for Windows without changing this server.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name COUNT and non-recursive in the prompt

Ask for COUNT equals n and only one directory level.
Run the harness and read which output lines still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep Usage on stderr with exit 1

Bad argument counts must print Usage and leave with status 1.
Ask the AI to keep that contract even if it rewrites help text.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये COUNT आणि non-recursive सांगा

COUNT समान n आणि फक्त एक directory level मागा.
Harness चालवा आणि अजून fail होणारे output वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Usage stderr वर आणि exit 1 ठेवा

चुकीच्या arguments साठी Usage छापून status 1 द्या.
AI help text बदलले तरीही हा करार ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. What does set -euo pipefail help with in Bash?

Exit on errors, treat unset variables as errors, and catch failures in pipes.

2. Where does our Bash script put the copy?

$HOME/backups/<folder-name>-YYYYMMDD-HHMMSS.

3. Why test on mktemp -d first?

So a bug cannot damage real project files.

4. Name one dangerous pattern to refuse in agent mode.

curl … | bash, or rm -rf on an unchecked variable.

Save tokens and money

SMART AI USE

Ask for one short script, not a whole deploy framework. Reuse the same backup prompt for new folders. Paste only the error line when a script fails.

Save these cards

INTERVIEW CARDAI Coding

How do you safely accept an AI shell script?

Require set -euo pipefail (Bash) or Stop on errors (PowerShell).
Test on a temp folder; refuse unchecked rm and curl|bash.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Bash vs PowerShell

Bash: default on Linux/Mac servers.
PowerShell: native on Windows; also runs on Linux as pwsh.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Shell with AI in 3

Name the shell + inputs.
Safe mode flags + clear Usage.
Dry-run on temp, then real paths.
Ravindra Bagale · ravindrabagale.com/ai-coding