Interview › Scripting (Bash, Groovy)
How do you write and call a function in Bash? [Basic]
Answer
A Bash function is a reusable block defined as name() { commands; } or function name { commands; }. I call it by writing its name followed by arguments, just like a command.
Technical explanation
Functions share the shell process with the caller, so they can read variables, set globals, and return statuses.
Use local variables inside functions to avoid accidental global state changes.
Functions improve readability when a script has validation, logging, cleanup, retries, and separate action steps.
Hands-on example
log() { printf '[%s] %s\n' "$(date +%F_%T)" "$*"}
deploy() { local env="$1" log "deploying to $env"}
deploy prodPreparing 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 pass arguments to a function and return a value or status? [Basic]
- What does IFS do, and why set it when reading lines? [Basic]
- What is local scope in a Bash function? [Basic]
- How do you write a for loop over a list and a C-style for loop? [Basic]
- What is OPTARG, and how does getopts handle options with values? [Intermediate]
- What is a here-string (<<<), and how does it differ from a here-doc? [Intermediate]
- What is the difference between >, >>, and 2> redirection? [Intermediate]
- What are the common file test operators (-f, -d, -e, -r, -w, -x)? [Basic]