Return value

2 snippets across 2 stacks - Bash & Linux, Python

SHBash & Linux

Functions

SH · Bash Scripting
Syntax
function_name() {
  commands
  return exit_code
}
Example
log_msg() {
  local level="$1"
  local message="$2"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [${level}] ${message}"
}

log_msg "INFO" "Deployment started"
log_msg "ERROR" "Config file missing"
Output
[2026-04-04 14:22:01] [INFO] Deployment started
[2026-04-04 14:22:01] [ERROR] Config file missing

Note Use local to scope variables to the function (without local, variables are global). Arguments are accessed via $1, $2, etc. $@ is all arguments. return sets the exit code (0-255); to return strings, echo them and capture with $().

PYPython

Defining Functions

PY · Functions
Syntax
def name(params):
    """docstring"""
    return value
Example
def greet(name: str, greeting: str = "Hello") -> str:
    """Build a personalized greeting."""
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", greeting="Hey"))
Output
Hello, Alice!
Hey, Bob!

Note Functions without an explicit return statement return None. Docstrings are accessible via help(func) and func.__doc__.

Frequently asked questions

How does Bash & Linux handle return value?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Functions" snippet in Bash & Linux uses `function_name() {`.
Which command does the Bash & Linux example use?
The "Functions" snippet uses `function_name() {`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "return value" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Functions": Use local to scope variables to the function (without local, variables are global). Arguments are accessed via $1, $2, etc. $@ is all arguments. return sets the exit code (0-255); to return strings, echo them and capture with $().