|
Size: 875
Comment:
|
← Revision 3 as of 2023-01-30 02:01:58 ⇥
Size: 1179
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 19: | Line 19: |
| A function's name must match `[a-zA-Z_][a-zA-Z0-9_]*`. |
|
| Line 35: | Line 37: |
| 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. | Arguments passed to a function implicitly overwrite the [[Shell/Variables#Positional_Variables|positional variables]] as well as the [[Shell/Variables#Special_Variables|argument count variable]] (`$#`). All of these will be reset to the original values upon the function's return. |
| Line 43: | Line 45: |
| 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. | 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. |
| Line 45: | Line 47: |
| The `return` builtin causes the function to return immediately. | 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 }}} |
Shell Function
Declaration
A function is declared like:
myfunction() {
:
}A function's name must match [a-zA-Z_][a-zA-Z0-9_]*.
Usage
The above function would be called like:
myfunction "first argument" "second argument"
Arguments
Arguments passed to a function implicitly overwrite the positional variables 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.
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