All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
1.5 KiB
1.5 KiB
Functions
Functions organize your code for reuse. Here's the structure:
function_name() {
your_commands
}
You can also use the function keyword for clarity, though it's optional:
function function_name() {
your_commands
}
Example: A simple 'Hello World!' function.
touch hello_function.sh
Open hello_function.sh and add:
#!/usr/bin/env bash
function hello() {
echo "Hello World Function!"
}
hello # Call the function (no parentheses)
Save and exit. Make it executable and run:
chmod +x hello_function.sh
./hello_function.sh
Functions accept arguments just like scripts.
touch function_args.sh
Open function_args.sh and add:
#!/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:
chmod +x function_args.sh
./function_args.sh
Document your functions clearly. Include a description, arguments, and expected output/return values.
#######################################
# 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.