return

Return from a function or sourced script.

Source: src/execution/builtins.f90:2510-2539

Synopsis

return [n]

Description

Exits the current function or sourced script with exit status n. If n is omitted, the exit status is that of the last command executed.

return is only valid inside a function or a sourced script. Outside these contexts, it sets $? to 2 with no other effect.

Arguments

ArgumentDescription
nReturn status (integer). Optional — defaults to $?

Context Requirements

ContextBehavior
Inside a functionExits the function
Inside a sourced scriptExits the sourced script
Top-level (neither)Sets $? to 2, no other effect

Examples

check_file() {
    if [[ ! -f "$1" ]]; then
        return 1
    fi
    return 0
}

if check_file "/etc/passwd"; then
    echo "File exists"
fi

Returning Data

return only provides a numeric status. To return data, use command substitution or a global variable:

# Command substitution
get_hostname() {
    hostname -s
}
result=$(get_hostname)

# Global variable
get_hostname() {
    RESULT=$(hostname -s)
}
get_hostname
echo "$RESULT"

Exit Status

StatusCondition
nThe provided return code
$?Last command's status, if no argument given
2Non-numeric argument, or called outside a function/source

See Also