| Start |
|---|
| Functions with arguments In **Note:** for arguments more than 9 `$10` won't work (bash will read it as **$1**0), you need to do `${10}`, `${11}` and so on. **Note:** You should practically always use double quotes around `"$@"`, like here.Omitting the quotes will cause the shell to expand wildcards (even when the user specifically quoted them in order to avoid that) and generally introduce unwelcome behavior and potentially even security problems. for default arguments use `${1:-default_val}`. Eg: Note: You should practically always use double quotes around |
| Simple Function In In running the script, we see our message Note that sourcing (opens new window) a file with functions makes them available in your current bash session. You can |
| Handling flags and optional parameters The getopts builtin can be used inside functions to write functions that accommodate flags and optional parameters. This presents no special difficulty but one has to handle appropriately the values touched by getopts. As an example, we define a failwith function that writes a message on stderr and exits with code 1 or an arbitrary code supplied as parameter to the This function can be used as follows: and so on. Note that as for printf, variables should not be used as first argument. If the message to print consists of the content of a variable, one should use the |
| Return value from a function The If you want to return a value from the function then send the value to Now, if you do: the output of |
| The exit code of a function is the exit code of its last command Consider this example function to check if a host is up: This function sends a single ping to the host specified by the first function parameter.
The output and error output of This fact is very useful in conditional statements. For example, if host Another example: repeatedly check until host |
Print the function definition Output: |
A function that accepts named parameters Example usage: Syntax} (): } function keyword and (): } |
Read Article
https://develop.horje.com/learn/1434/reference