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 2

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

← All Scripting (Bash, Groovy) questions