Files
linux.softwareshinobi.com/landing/docs/Bash-Scripts/012-bash-functions.md
Software Shinobi 7d9171c854
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
reworking content
2025-06-19 10:03:08 -04:00

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.