Interview › Scripting (Bash, Groovy)
How do you pass arguments to a function and return a value or status? [Basic]
Answer
Function arguments are accessed as $1, $2, and so on inside the function. A function returns a status with return, and returns data by printing to stdout, setting a variable by reference pattern, or writing to a file/stream.
Technical explanation
return is only for numeric exit status from 0 to 255; it is not a general data return mechanism.
Use command substitution to capture stdout from a function when returning a string.
For robust scripts, separate data on stdout from logs/errors on stderr.
Hands-on example
get_image_tag() { local branch="$1" local sha="$2" printf '%s-%s\n' "$branch" "$sha"}
tag=$(get_image_tag "main" "abc123")
echo "tag=$tag"
validate_env() { [[ "$1" =~ ^(dev|stage|prod)$ ]]; }validate_env prod || exit 2Preparing 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
- 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]