Skip to content

[Term Entry]Command line Bash: Functions #6941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
278 changes: 278 additions & 0 deletions content/command-line/concepts/bash/terms/functions/functions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,278 @@
---
Title: 'Functions'
Description: 'Creates reusable blocks of code that group commands under a single name for modular scripting.'
Subjects:
- 'Bash/Shell'
- 'Computer Science'
Tags:
- 'Bash/Shell'
- 'Command Line'
- 'Functions'
CatalogContent:
- 'learn-the-command-line'
- 'paths/computer-science'
---

A **function** in Bash is a reusable block of code that groups a set of commands under a single name. Functions enable you to organize code into logical units, reduce repetition, and make scripts more maintainable and readable. When called, a function executes all the commands within its body and can optionally return a value to the calling code.

Functions are essential building blocks in Bash scripting for automating repetitive tasks, creating modular code architecture, and implementing complex workflows. They are commonly used in system administration scripts, deployment automation, data processing pipelines, and interactive command-line tools where the same operations must be performed multiple times with different inputs.

## Syntax

```pseudo
function_name() {
# Commands to execute
command1
command2
# ...
}

# Calling the function
function_name
```

**Alternative syntax:**

```pseudo
function function_name {
# Commands to execute
command1
command2
# ...
}

# Calling the function
function_name
```

**Parameters:**

- `function_name`: The name identifier for the function. Should be descriptive and follow naming conventions
- `{ }`: Curly braces that define the function body containing the commands to execute
- `command1`, `command2`: The actual Bash commands that will be executed when the function is called

**Arguments and Return Values:**

- Functions can accept arguments accessed through `$1`, `$2`, `$3`, etc., representing the first, second, third arguments respectively
- `$#` contains the number of arguments passed to the function
- `$@` and `$*` represent all arguments passed to the function
- Functions return the exit status of the last executed command, or an explicit value using `return`

## Example 1: Basic Function Creation

This example demonstrates how to create and call a simple function that displays a greeting message:

```bash
#!/bin/bash

# Define a simple greeting function
greet_user() {
echo "Welcome to Bash scripting!"
echo "Today's date is: $(date +%Y-%m-%d)"
echo "Have a productive day!"
}

# Call the function
echo "Starting the program..."
greet_user
echo "Program completed."
```

The output of the above code will be:

```shell
Starting the program...
Welcome to Bash scripting!
Today's date is: 2025-05-30
Have a productive day!
Program completed.
```

This example shows the basic structure of a Bash function. The `greet_user()` function is defined with three echo commands that display welcome messages and the current date. The function is then called by simply using its name. The function definition must appear before any calls to the function in the script.

## Example 2: Function with Parameters

This example demonstrates how to create a function that accepts parameters and uses them to perform calculations:

```bash
#!/bin/bash

# Function to calculate the area of a rectangle
calculate_area() {
local length=$1 # First argument
local width=$2 # Second argument

# Validate input parameters
if [ $# -ne 2 ]; then
echo "Error: Function requires exactly 2 arguments (length and width)"
return 1
fi

# Calculate area
local area=$((length * width))

# Display results
echo "Rectangle dimensions: ${length} x ${width}"
echo "Calculated area: ${area} square units"

# Return the area for potential use by calling code
return 0
}

# Test the function with different parameters
echo "=== Area Calculator ==="
calculate_area 5 3
echo ""
calculate_area 12 8
echo ""
calculate_area 7 # This will trigger an error
```

The output generated by this code will be:

```shell
=== Area Calculator ===
Rectangle dimensions: 5 x 3
Calculated area: 15 square units

Rectangle dimensions: 12 x 8
Calculated area: 96 square units

Error: Function requires exactly 2 arguments (length and width)
```

This example illustrates how functions can accept and process parameters. The `calculate_area()` function takes two arguments (length and width), validates the input, performs arithmetic operations, and provides feedback. The `local` keyword ensures variables are scoped to the function, preventing conflicts with global variables.

## Example 3: System Information Utility

This example shows a practical function for gathering and displaying system information, demonstrating real-world usage:

```bash
#!/bin/bash

# Function to display comprehensive system information
show_system_info() {
local info_type=${1:-"all"} # Default to "all" if no parameter provided

echo "=== System Information Report ==="
echo "Generated on: $(date)"
echo ""

case $info_type in
"basic"|"all")
echo "--- Basic System Info ---"
echo "Hostname: $(hostname)"
echo "Operating System: $(uname -s)"
echo "Kernel Version: $(uname -r)"
echo "Architecture: $(uname -m)"
echo ""
;& # Fall through to next case
"resources"|"all")
echo "--- System Resources ---"
echo "CPU Information:"
echo " Processor: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2 | xargs)"
echo " CPU Cores: $(nproc)"
echo ""
echo "Memory Information:"
echo " Total RAM: $(free -h | grep 'Mem:' | awk '{print $2}')"
echo " Available RAM: $(free -h | grep 'Mem:' | awk '{print $7}')"
echo ""
echo "Disk Usage:"
df -h / | tail -1 | awk '{print " Root partition: " $3 " used of " $2 " (" $5 " full)"}'
echo ""
;&
"network"|"all")
if [ "$info_type" = "network" ] || [ "$info_type" = "all" ]; then
echo "--- Network Information ---"
echo "IP Address: $(hostname -I | awk '{print $1}')"
echo "Network Interfaces:"
ip -o link show | awk '{print " " $2}' | sed 's/://'
echo ""
fi
;;
*)
echo "Error: Invalid info type. Use 'basic', 'resources', 'network', or 'all'"
return 1
;;
esac

echo "Report generation completed."
return 0
}

# Demonstrate function usage with different parameters
echo "Generating full system report:"
show_system_info
echo -e "\n" | head -2

echo "Generating basic info only:"
show_system_info "basic"
```

The output of this code will be:

```shell
Generating full system report:
=== System Information Report ===
Generated on: Fri May 30 12:00:00 UTC 2025

--- Basic System Info ---
Hostname: myserver
Operating System: Linux
Kernel Version: 5.4.0-74-generic
Architecture: x86_64

--- System Resources ---
CPU Information:
Processor: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
CPU Cores: 8

Memory Information:
Total RAM: 16Gi
Available RAM: 12Gi

Disk Usage:
Root partition: 45G used of 100G (45% full)

--- Network Information ---
IP Address: 192.168.1.100
Network Interfaces:
lo
eth0
wlan0

Report generation completed.


Generating basic info only:
=== System Information Report ===
Generated on: Fri May 30 12:00:00 UTC 2025

--- Basic System Info ---
Hostname: myserver
Operating System: Linux
Kernel Version: 5.4.0-74-generic
Architecture: x86_64

Report generation completed.
```

This advanced example demonstrates a utility function that gathers system information. It showcases parameter handling with default values, conditional logic using case statements, command substitution for gathering system data, and practical system administration tasks. The function can be called with different parameters to display specific types of information.

## Frequently Asked Questions

### 1. Can I use variables declared inside a function outside of it?

By default, variables in Bash functions are global unless explicitly declared with the `local` keyword. However, it's best practice to use `local` for variables that should only exist within the function to avoid naming conflicts and unexpected behavior.

### 2. How do I return values from a Bash function?

Bash functions can return exit status codes (0-255) using the `return` command. For returning actual data, you can use `echo` to output the result and capture it with command substitution: `result=$(my_function)`.

### 3. What happens if I don't provide the required arguments to a function?

The function will still execute, but the missing arguments will be empty. You should implement input validation within your functions to check for required parameters using conditional statements and the `$#` variable.

### 4. Can I call a function before defining it in the script?

No, function definitions must appear before any calls to the function in the script. Bash reads and processes the script sequentially, so the function must be known before invoking it.