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 "$@"
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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]