Bash Functions: Writing Reusable Commands

Learn how to create reusable Bash functions to avoid repetition and organize your shell commands. Covers basic function syntax, parameters, return values, and practical examples for daily use.

Bash Functions: Writing Reusable Commands

Functions in Bash are like creating your own custom commands. Instead of typing the same sequence of commands repeatedly, you can bundle them into a reusable function that executes with a single name. Think of functions as shortcuts that make your shell work more efficient and your scripts more organized.

What Are Bash Functions?

A Bash function is a group of commands that you can call by name. Once defined, you can use your function just like any built-in command. Functions help you avoid repetition, make your code more readable, and create powerful custom tools.

Here's the basic syntax for defining a function:

function_name() {
    # commands go here
    command1
    command2
}

Writing Your First Function

Let's start with a simple example. Suppose you frequently need to check disk usage in a readable format. Instead of typing df -h every time, create a function:

diskspace() {
    echo "Disk usage information:"
    df -h
}

To use this function, simply type diskspace and press Enter. The function executes both the echo command and df -h in sequence.

You can define functions directly in your terminal for immediate use, or add them to your ~/.bashrc file to make them available every time you open a new shell session.

Functions with Parameters

Functions become much more powerful when they accept parameters. Inside a function, you can access parameters using $1 for the first parameter, $2 for the second, and so on. The special variable $@ represents all parameters.

Here's a function that creates a directory and immediately changes into it:

mkcd() {
    mkdir -p "$1"
    cd "$1"
}

Use it like this: mkcd new_project. This creates the directory "new_project" and changes your current location to it in one command.

Here's a more advanced example that searches for files containing specific text:

findin() {
    if [ $# -ne 2 ]; then
        echo "Usage: findin  "
        return 1
    fi
    
    grep -r "$2" "$1" 2>/dev/null
}

This function checks that exactly two parameters are provided, then searches recursively in the specified directory for the given text.

Return Values and Local Variables

Functions can return exit codes using the return statement. A return value of 0 indicates success, while non-zero values indicate different types of errors:

check_file() {
    if [ -f "$1" ]; then
        echo "File $1 exists"
        return 0
    else
        echo "File $1 not found"
        return 1
    fi
}

Use the local keyword to create variables that exist only within the function, preventing conflicts with global variables:

backup_file() {
    local filename="$1"
    local backup_dir="$HOME/backups"
    
    mkdir -p "$backup_dir"
    cp "$filename" "$backup_dir/$(basename "$filename").bak"
    echo "Backed up $filename"
}

Practical Function Examples

Here are some useful functions for daily work:

# Extract various archive formats
extract() {
    if [ -f "$1" ]; then
        case $1 in
            *.tar.bz2)   tar xjf "$1"     ;;
            *.tar.gz)    tar xzf "$1"     ;;
            *.zip)       unzip "$1"       ;;
            *.rar)       unrar x "$1"     ;;
            *)           echo "Unknown archive format" ;;
        esac
    else
        echo "File not found: $1"
    fi
}

# Quick web server for current directory
webserver() {
    local port=${1:-8000}
    python3 -m http.server "$port"
}

The webserver function demonstrates parameter defaults - if no port is specified, it uses 8000.

What's Next

Now that you understand basic function creation, the next step is learning about Bash arrays and how to process multiple values efficiently. Arrays work particularly well with functions to handle lists of files, directories, or configuration options in your scripts.

🔧
Use a good text editor with syntax highlighting and shell integration to write and debug your bash functions more effectively. Visual Studio Code, Sublime Text and vim.
🔧
Version control your bash functions with Git so you can easily sync your custom commands across all your systems. Git, GitHub and dotfiles repository.