Interview › Scripting (Bash, Groovy)
How would you structure a large script into reusable functions and a main entry point? [Advanced]
Answer
I structure a large script with a small main function, focused helper functions, clear global constants, argument parsing, validation, logging, cleanup traps, and a final main "$@" entry point. This makes the script testable and readable.
Technical explanation
Keep functions single-purpose, such as parse_args, validate_inputs, acquire_lock, deploy, verify, and cleanup.
Avoid running substantial logic at import/source time if the file may be reused as a library.
For very large logic, move to Python or another maintainable language with unit tests and packages.
Hands-on example
#!/usr/bin/env bash
set -euo pipefail
log() { printf '[%s] %s\n' "$(date +%FT%T%z)" "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
parse_args() {
ENVIRONMENT=${1:-}
[[ -n "$ENVIRONMENT" ]] || die "env required"
}
validate() { command -v kubectl >/dev/null || die "kubectl missing"; }
run() { log "deploying to $ENVIRONMENT"; }
main() { parse_args "$@"; validate; run; }
main "$@"Preparing for an interview?
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Scripting (Bash, Groovy) interview questions
- How do you write a dry-run mode into an automation script, and why is it valuable? [Advanced]
- What is the difference between Groovy and Java for scripting purposes? [Advanced]
- How do you run stages in parallel in a Jenkins Groovy pipeline? [Advanced]
- How do you handle errors and retries in a Groovy pipeline (try/catch, retry, timeout)? [Advanced]
- How do you define and call a function (or step) in a Jenkins Groovy pipeline? [Advanced]
- How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
- What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]