Shell scripts
Goal
A script that does the job, fails loudly instead of silently, and is safe to run twice. A good result states what it will change before anyone runs it.
When to use
- The user wants a bash, PowerShell or cmd script to automate something.
- The user wants a one-liner explained or a script fixed.
- For a CI pipeline file, use
use_skillwithci-workflow. - For a container build file, use
use_skillwithdockerfile.
Steps
- Pick the shell to match the user's system and project: PowerShell on Windows (pwsh 7 when available), bash for Linux, macOS and CI. Ask if unclear.
- For bash:
- Start with
#!/usr/bin/env bashandset -euo pipefail. - Quote every variable:
"$file","${items[@]}". Use[[ ... ]]for tests. - Use
mktempfor temporary files andtrap 'rm -f "$tmp"' EXITto clean up. - Loop over files with
find ... -print0 | while IFS= read -r -d '' f; do ...or globs withshopt -s nullglob. - Check required commands:
command -v jq >/dev/null || { echo "jq is required" >&2; exit 1; }. - Print errors to stderr and exit non-zero on failure.
- Start with
- For PowerShell:
- Set
$ErrorActionPreference = 'Stop'andSet-StrictMode -Version Latest. - Use approved Verb-Noun function names,
param()with types, and-LiteralPathfor paths that may contain brackets. - Use
-WhatIfthroughSupportsShouldProcessfor destructive functions. - Pass objects through the pipeline instead of parsing text when cmdlets return objects.
- Set
- For every script:
- Add a usage message (
-hor--help) and argument validation. - Add a dry-run option for anything that deletes, moves or overwrites, showing what would happen.
- Make it idempotent where possible.
- Read secrets from environment variables, never hardcode them.
- Add a usage message (
- Test:
- In Code, save the script with
write_fileand run it withrun_commandin dry-run mode on a safe test folder first. Ask before running it for real on anything that deletes or changes files outside the project. - In Chat, where commands cannot run, save it with
create_fileif the user wants a file and explain how to run it. Script extensions such as .sh or .ps1 may be refused for safety. In that case give the script in the reply to copy.
- In Code, save the script with
Gotchas
- Bash-only syntax does not run in cmd or PowerShell. Match the shell.
- An unquoted variable breaks on spaces and can expand into something destructive.
- Never parse
lsoutput. Use globs orfind -print0. - A script that deletes with no dry-run option cannot be checked before it does damage.
- Running a destructive script outside the project without asking is not acceptable, even as a test.
Output
The script in a code block, what it does step by step, how to run it (including making it executable on Unix), and what it changes.
