Around Go: command line · 3 MIN READ

Small scripts: arguments, environment and cleanup

Read required configuration, forward quoted arguments and clean a temporary workspace with a trap.

A useful script has explicit inputs and predictable cleanup. Bash distinguishes positional arguments, shell variables and exported environment. This lesson puts those pieces into a small test wrapper instead of assuming that adding set -e makes every failure path correct.

01

Read arguments and pass a setting to one process

${1:-.} supplies a default when the first argument is absent or empty. A prefix assignment affects one command environment; export affects later child processes from this shell. Neither changes an already running service.

bash
project_dir="${1:-.}"
printf "Testing: %s\n" "$project_dir"
GOMAXPROCS=2 go -C "$project_dir" test ./...
export APP_ENV=development
printf "APP_ENV=%s\n" "$APP_ENV"
Read the code

The Go -C flag precedes the test command. The temporary GOMAXPROCS assignment does not permanently change your shell. Never print the complete environment to diagnose one non-secret setting.

02

Validate inputs and clean only owned temporary data

The : command with ${name:?message} reports a required input. mktemp creates the workspace, and EXIT runs cleanup on ordinary shell termination. The script forwards "$@" as separate arguments and uses an explicit test branch to preserve failure.

bash
#!/usr/bin/env bash
set -u
: "${PROJECT_DIR:?Set PROJECT_DIR to a Go project}"
work_dir=$(mktemp -d) || exit 1
trap 'rm -f "$work_dir/test.log"; rmdir "$work_dir"' EXIT
if go -C "$PROJECT_DIR" test "$@" ./... > "$work_dir/test.log" 2>&1; then
    cat "$work_dir/test.log"
else
    cat "$work_dir/test.log" >&2
    exit 1
fi
Read the code

Save this as check.sh and call it with bash, PROJECT_DIR set, and optional go test flags such as -count=1. The trap names the one file it owns. SIGKILL and machine failure cannot run shell cleanup.

03

Check syntax before running the script

bash -n parses without executing the script; it does not prove that command names, paths or remote systems exist. --help or command -v can establish what is installed. Review changes before making a script executable or putting it into CI.

bash
bash -n check.sh
command -v bash
command -v go
PROJECT_DIR="$PWD" bash check.sh -count=1
Read the code

Syntax success is silent. The final line runs tests and can download required Go modules; it is an execution step, not another parser check. Keep credentials out of arguments and traces such as bash -x.

TAKE THIS WITH YOU

A script should declare its inputs, preserve argument boundaries and clean only resources it created. Parsing, executing and validating its external effects are separate checks.

Check your understanding

What changes when you export APP_ENV?

Go to the source

Progress stays in this browser. No account needed.