Size: 1123
Comment:
|
Size: 1355
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 47: | Line 47: |
=== Local Scope === To mark a variable as belonging only to a function's scope, declare it with the `local` [[Bash/BuiltinCommands#Local|builtin]]. {{{ local x=y }}} |
|
Line 61: | Line 71: |
if isdirectory "$some_directory"; then : fi |
Bash Function
Declaration
A function is declared with one of:
myfunction() { : } function myfunction() { : }
If the function keyword is used, the parentheses are optional.
Usage
The above functions would be called like:
myfunction "first argument" "second argument"
Arguments
Arguments passed to a function implicitly overwrite the positional variables ($1, $2, and so on) as well as the argument count variable ($#). All of these will be reset to the original values upon the function's return.
Note that $0 is not overwritten.
Local Scope
To mark a variable as belonging only to a function's scope, declare it with the local builtin.
local x=y
Error and Return Codes
By default a function does not set the exit code. But it also does not clear the code. The final command in a function effectively sets the error code for the function as well.
The return builtin causes the function to return immediately with a specified exit code.
isdirectory() { if [ -d "$1" ]; then return 0 else return 1 fi } if isdirectory "$some_directory"; then : fi