Functions
Functions in Bash are named blocks of shell commands. Bash executes the block in the current shell environment when we call the function. Two common ways to define them:function keyword is Bash-specific. We call a function just by its name: my_func.
Local Variables
Assignments inside a function affect global variables by default. If we want a variable local to the function call, we use thelocal keyword:
var temporarily hides the global var, so changing it does not change the global value. Bash uses dynamic scoping, which means functions called from my_func can also see this local variable while my_func is running.
Passing Parameters
We pass parameters to functions the same way as script arguments — they are accessed with$1, $2, etc. inside the function:
Return Values
Bash functions return an exit status from0 to 255, not a general value like a C function. Some common statuses are:
We set a function’s status with
return N. Without an explicit return, the function uses the status of its last command. We access the most recent exit status with $?.