Functions
-
functions can be terminated using
returnORexit-
in Bash,
returndoes not pass a data value like in C++ or Java; it only passes an exit status code (a number between 0 and 255).Terminal window check_network() {ping -c 1 google.com > /dev/null 2>&1if [ $? -eq 0 ]; thenreturn 0 # Successelsereturn 1 # Failurefi}Risk Explanation The 255 Limit Exit codes are 8-bit integers. If your math result is 256, returnwill give you 0. If it is 257, it gives you 1. It “wraps around”.Status vs. Data In Linux, 0usually means “Success” and non-zero means “Error”. Usingreturnfor math flips this logic and can confuse other parts of your script.Immediate Capture You must use $?immediately. If you run any other command (even anecho) between the function call and$?, the value will be overwritten by the new command’s status.
-
-
localused to define local variables inside function which are different from outside variables..- TIP: if we try to access a variable in bash which is not defined.. we won’t get any errors!!! instead it prints empty value..



Possible Function Sytaxes and stuff…
Section titled “Possible Function Sytaxes and stuff…”-
name() { ... }: Standard syntax; the most portable and common way to define a function. -
function name { ... }: Alternative syntax using thefunctionkeyword; parentheses are optional here. -
function name() { ... }: Combined syntax; works in Bash but is redundant. -
name() { command; }: Single-line syntax; requires a space after{and a semicolon before}. -
local var=$1: Variable scope limiter; restricts a variable’s existence to the function execution. -
$1, $2, ... $n: Positional parameters; accesses arguments passed to the function by their order. -
$#: Argument counter; returns the total number of arguments passed to the function. -
$@: All-arguments list; represents every passed argument as a distinct quoted string. -
return n: Exit status; stops the function and returns a numeric code (0–255) to the caller. -
$(name): Command substitution; captures theechooutput of a function into a variable. -
name() { ... } > file: Function redirection; sends all standard output from the function into a specific file. -
outer() { inner() { ... }; }: Nested definition; defines a function inside another (inner becomes global once outer runs).Terminal window parent_func() {echo "This is the parent."child_func() {echo "This is the child, nested inside."}child_func # Calling it inside the parent}# child_func # This would fail here (not defined yet)parent_func # Runs parent and defines childchild_func # Now this works globally!
Example

