88 lines
1.5 KiB
Markdown
88 lines
1.5 KiB
Markdown
|
|
# Functions
|
||
|
|
|
||
|
|
Functions organize your code for reuse. Here's the structure:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
function_name() {
|
||
|
|
your_commands
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
You can also use the `function` keyword for clarity, though it's optional:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
function function_name() {
|
||
|
|
your_commands
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
Example: A simple 'Hello World!' function.
|
||
|
|
|
||
|
|
```bash
|
||
|
|
touch hello_function.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Open `hello_function.sh` and add:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
function hello() {
|
||
|
|
echo "Hello World Function!"
|
||
|
|
}
|
||
|
|
|
||
|
|
hello # Call the function (no parentheses)
|
||
|
|
```
|
||
|
|
|
||
|
|
Save and exit. Make it executable and run:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
chmod +x hello_function.sh
|
||
|
|
./hello_function.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Functions accept arguments just like scripts.
|
||
|
|
|
||
|
|
```bash
|
||
|
|
touch function_args.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Open `function_args.sh` and add:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
function greet_team() {
|
||
|
|
echo "Hello $1!"
|
||
|
|
}
|
||
|
|
|
||
|
|
greet_team "Dev Team Six" # Pass argument when calling
|
||
|
|
```
|
||
|
|
|
||
|
|
Save and exit. Make it executable and run:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
chmod +x function_args.sh
|
||
|
|
./function_args.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Document your functions clearly. Include a description, arguments, and expected output/return values.
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#######################################
|
||
|
|
# Description: Greets a single argument.
|
||
|
|
# Globals: None
|
||
|
|
# Arguments:
|
||
|
|
# $1 - Name/value to greet.
|
||
|
|
# Outputs:
|
||
|
|
# Prints a greeting to stdout.
|
||
|
|
# Returns:
|
||
|
|
# 0 on success.
|
||
|
|
#######################################
|
||
|
|
function greet_example() {
|
||
|
|
echo "Greeting: $1"
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
Functions are key to building organized and reusable Bash scripts. Master them for efficient automation.
|