WCC logo

CIS120Linux Fundementals

Bash Functions

Syntax Variations

Without parentheses:

function_name {
    # Commands
}

With parentheses:

function_name() {
    # Commands
}

Differences and Similarities

Function Keyword (Optional):

In some variations, you might see the function keyword used to define a function. This is optional and generally not necessary in modern Bash scripting. However, when using the function keyword, the parentheses are typically omitted:

function function_name {
    # Commands
}

Parentheses:

The use of parentheses () is optional in Bash. They are commonly used for clarity and readability to explicitly indicate a function definition. Function definitions with parentheses are more common and align with the style of many other programming languages, making the script easier to understand for people with experience in those languages.

POSIX Compliance:

The syntax function_name() { ... } is more aligned with POSIX standards and is preferred for writing scripts intended to be portable across different Unix-like systems. The function keyword is not POSIX-compliant and is specific to Bash and some other shells like Zsh and Ksh.

Variable Scope:

There is no difference in how variables are scoped within the function based on the syntax used to define the function. Both styles allow the use of local variables within the function using the local keyword.

Here's a simple example of a function that prints a greeting message:

#!/bin/bash

# Define a function
greet() {
    echo "Hello, World!"
}

# Call the function
greet

In this script, the greet function is defined to print "Hello, World!" and is then called to execute its commands. Note that functions in Bash can be defined with or without parentheses. The use of parentheses is a common convention to clearly indicate the function definition, although they are not strictly necessary if no parameters are being passed.

Returning Values from Functions

Bash functions can return status codes using the return command. The return value is an integer between 0 and 255, where 0 typically signifies success, and any non-zero value indicates an error. Bash functions cannot return string or numeric values directly using return. Instead, you can use echo or variable assignment to get these values out of a function.

Here’s an example of a function that returns a status code:

#!/bin/bash

# Define a function that checks if a number is positive
is_positive() {
    if [ $1 -gt 0 ]; then
        return 0  # Success
    else
        return 1  # Failure
    fi
}

# Call the function with a number
is_positive 5
status=$?

if [ $status -eq 0 ]; then
    echo "The number is positive."
else
    echo "The number is not positive."
fi

In this script, the is_positive function checks if a given number (passed as an argument) is positive. The function returns 0 if the number is positive and 1 otherwise. The return status is captured in the $? variable and used to print an appropriate message.

Scoping in Bash Functions

Variables in Bash have a global scope by default, meaning they are accessible throughout the script, including inside functions. To create local variables within a function, you can use the local keyword. Local variables are only accessible within the function where they are defined.

Here’s an example demonstrating variable scoping:

#!/bin/bash

# Global variable
message="Hello, World!"

# Define a function
print_message() {
    local message="Hello, Local World!"
    echo $message
}

# Call the function
print_message

# Print the global variable
echo $message

In this script:

Passing Arguments to Functions

Functions in Bash can accept arguments. These arguments are accessed using positional parameters $1, $2, and so on, within the function.

Here’s an example of a function that takes arguments:

#!/bin/bash

# Define a function that prints a greeting message
greet() {
    echo "Hello, $1!"
}

# Call the function with an argument
greet "Alice"

In this script, the greet function takes one argument and prints a greeting message using that argument. When calling the function with "Alice" as the argument, it prints "Hello, Alice!".

Here is another example that takes multiple arguments. The arguments are in order so $1 = 5, $2 = 2 and $3 = 6


add(){
    echo "The numbers added together are $(($1 + $2 + $3))"
}
    
add 5 2 6

If you don't have the correct number of arguments you will get an error. The code below would generate an error.


add(){
    echo "The numbers added together are $(($1 + $2 + $3))"
}
    
add 5 2

If you use a number character in string bash will infer that it is a number. The code below will generate 12 as the answer.


add(){
    echo "The numbers added together are $(($1 + $2 + $3))"
}
    
add 5 2 "5"

If you add a alpha string it will just omit it. Here it returns 7 because it does not know what to do with "scott"


add(){
    echo "The numbers added together are $(($1 + $2 + $3))"
}
    
add 5 2 "scott"

Summary

Functions in Bash scripts are powerful tools that help organize and reuse code. They can accept arguments, return status codes, and have local variable scopes. By using functions, you can create more modular and maintainable scripts. Understanding how to define, call, and manage functions is essential for efficient Bash scripting. Functions help break down complex tasks into simpler parts, making scripts easier to read, debug, and maintain.