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
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
- 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
Step 1 — Bash prompt
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-HHMMSSStep 3 — same idea in 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 — 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
- Rules file: “Bash: set -euo pipefail; PowerShell: $ErrorActionPreference = 'Stop'; never rm -rf without an explicit dry-run flag”.
- Ask the AI to add a
--dry-runflag for any script that deletes or overwrites. - Quote every variable:
"$SRC", not bare$SRC(spaces in paths). - Prefer
cp -a/Copy-Itemover 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 $VARwhen 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.
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.
नमस्कार मित्रांनो. Live chapter मध्ये backup_folder.sh helper आधीच आला आहे. हा सराव Copper Lantern Labs नावाच्या वेगळ्या काल्पनिक लॅबवर आहे. तुम्ही AI कडून count_ext.sh हा Bash script मागता जो एका directory मध्ये (non-recursive) दिलेल्या extension चे फाइल मोजतो, COUNT समान संख्या छापतो, आणि चुकीच्या arguments साठी stderr वर Usage छापून exit 1 देतो. Windows विद्यार्थ्यांसाठी Count-Ext.ps1 हा PowerShell twin teaching text म्हणून दिला आहे. या drafting Linux मशीनवर आम्ही /usr/bin/bash ने pytest harness खाली Bash खरोखर चालवला: starter मध्ये सर्व 7 fail, आणि fixed मध्ये सर्व 7 पास. इथे pwsh नाही, म्हणून PowerShell चालवले नाही.
नमस्ते दोस्तों. Live chapter में backup_folder.sh helper पहले आ चुका है. यह अभ्यास Copper Lantern Labs नाम की अलग काल्पनिक लैब पर है. आप AI से count_ext.sh नाम का Bash script मांगते हो जो एक directory में (non-recursive) दिए गए extension वाली फाइलें गिने, COUNT बराबर संख्या छापे, और गलत arguments पर stderr पर Usage छापकर exit 1 दे. Windows विद्यार्थियों के लिए Count-Ext.ps1 PowerShell twin teaching text के रूप में शामिल है. इस drafting Linux मशीन पर हमने /usr/bin/bash से pytest harness के तहत Bash सच में चलाया: starter में सभी 7 fail, और fixed में सभी 7 पास. यहां pwsh नहीं है, इसलिए PowerShell नहीं चलाया।
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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये COUNT समान n, non-recursive matching, आणि stderr वर Usage सोबत exit 1 लिहा. Bash script च्या वर set -euo pipefail ठेवा, आणि Bash आधी सिद्ध केले तरीही Windows साठी PowerShell twin जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
Prompt में COUNT बराबर n, non-recursive matching, और stderr पर Usage के साथ exit 1 लिखो. Bash script के ऊपर set -euo pipefail रखो, और Bash पहले साबित करने पर भी Windows के लिए PowerShell twin बचाए रखो।
/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
- Create a project folder and open a terminal inside it.
- Save
count_ext.shand make it executable withchmod +x count_ext.sh. - Optional harness: copy
test_count_ext.pybeside the script and runpython3 -m pytest -q test_count_ext.py(needs pytest). - On Windows: keep
Count-Ext.ps1for PowerShell; this drafting box could not run pwsh.
Starter count_ext.sh (recursive, bare number, weak args):
#!/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.txtWrite 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
- Save the starter Bash script and make it executable.
- 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.
- Run the harness (or manual fixtures). On this drafting box the starter showed 7 failed.
- 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
- Problem: the script prints
3when a nested deep.txt exists beside two top-level txt files. Fix: count only direct children, not recursive find. - Problem: the script prints
2instead ofCOUNT=2. Fix: print the exactCOUNT=prefix the tests expect. - Problem: passing
.txtcounts zero files. Fix: strip a leading dot from the extension before matching. - Error: pwsh is missing on the drafting box. Fix: prove Bash here; keep
Count-Ext.ps1for 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.
Name COUNT and non-recursive in the prompt
Keep Usage on stderr with exit 1
Prompt मध्ये COUNT आणि non-recursive सांगा
Usage stderr वर आणि exit 1 ठेवा
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
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.