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
- How do you write and call a function in Bash? [Basic]
- What is local scope in a Bash function? [Basic]
- What does IFS do, and why set it when reading lines? [Basic]
- What is OPTARG, and how does getopts handle options with values? [Intermediate]
- How do you write a for loop over a list and a C-style for loop? [Basic]
- 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 does 2>&1 mean, and how do you redirect both stdout and stderr? [Intermediate]