Bash Functions: Stop Repeating Yourself (DRY)
In this article
- Why Repetition Is a Problem in Shell Scripts
- How Bash Functions Work: Definition and Scope
- Practical Examples: From Duplicated Code to Functions
- Later in the script
- ... do something
- Choosing Between Functions, Aliases, and Scripts
- Common Pitfalls and How to Avoid Them
- Performance and Readability Trade-offs
- DRY in Practice: A Small Case Study
- Frequently Asked Questions
Yes, using bash functions is a direct and effective way to stop repeating yourself and keep your code DRY (Don't Repeat Yourself). By wrapping a reusable command sequence in a named function, you write the logic once and call it many times, making scripts shorter, easier to maintain, and less error-prone.
Why Repetition Is a Problem in Shell Scripts
When you copy and paste the same block of commands multiple times, you introduce several risks. First, every copy is a place where a bug can hide. If you need to change a path, a flag, or a variable name, you must remember to update every single occurrence. Miss one, and your script behaves inconsistently. Second, repetition makes scripts longer and harder to read, which slows down debugging and review. DRY is a software engineering principle that applies just as much to a 50-line bash script as it does to a large application. Functions are the primary tool bash gives you to achieve DRY.
How Bash Functions Work: Definition and Scope
A bash function is defined using either function name { ...; } or simply name() { ...; }. The function body contains standard bash commands. When you call the function by name, bash executes those commands in the current shell context. This is a key difference from a separate script: a function runs in the same shell, so it can modify variables, change the current directory, and set options that affect the rest of the script. This makes functions powerful for DRY, but also means you must be careful about side effects.
Variables inside a function are global by default. To avoid clobbering a global variable, declare local ones with local. For example:
greet() {
local name="$1"
echo "Hello, $name!"
}
greet "Alice"Here, name is local to the function. The positional parameter $1 holds the first argument passed to the function. Functions can also return a status code using return, but they cannot directly return a string. To get a string output, you capture the function's stdout: result=$(greet "Bob").
Practical Examples: From Duplicated Code to Functions
Consider a script that needs to check if a user is root in three different places. Without a function, you might write the same if statement each time. With a function:
require_root() {
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" >&2
exit 1
fi
}
Later in the script
require_root
... do something
require_root # Call again if neededAnother common pattern is logging. Instead of repeating echo "[$(date)]: message" everywhere, define a log() function that adds a timestamp and writes to a log file. Then each call is just log "Backup started". This not only reduces repetition, but also centralizes the logging format. If you later want to add a log level or send output to syslog, you change only the function.
Choosing Between Functions, Aliases, and Scripts
Bash offers several ways to reuse code, and each has its place. Aliases are simple text substitutions that work well for short, interactive commands like alias ll='ls -alF'. They are not suitable for complex logic or for use in non-interactive scripts. Separate scripts are executable files that run in a subshell. They are good for standalone utilities, but they cannot easily modify the parent shell's environment. Functions are the best choice when you need to:
- Reuse a block of logic within a single script.
- Modify the current shell's variables or working directory.
- Keep related operations together in a library file that you can source.
If you have a set of functions that you use across many scripts, you can put them in a file and source that file with source /path/to/lib.sh or . /path/to/lib.sh. This is a common pattern for shell scripting libraries.
Common Pitfalls and How to Avoid Them
One frequent mistake is forgetting that a function runs in the current shell. If a function calls exit, it exits the entire script, not just the function. Use return to exit only the function. Another pitfall is naming a function the same as a built-in command or another function, which can lead to unexpected behavior. Always choose descriptive, unique names. Also, be careful with whitespace: the opening brace must be followed by a space or a newline, and the closing brace must be on its own line or preceded by a semicolon. Finally, remember that functions are not automatically available in subshells or child processes. If you define a function in a script and then call a script that expects it, you must source the definition first.
Performance and Readability Trade-offs
Functions add a tiny amount of overhead compared to inline code, but this is negligible in almost all cases. The real benefit is in maintainability. A script with functions is easier to read because each function has a name that describes what it does. It is also easier to test because you can call individual functions with specific inputs. However, overusing functions can fragment the logic and make it harder to follow the flow. The goal is to find a balance: use functions for repeated blocks of 3 or more lines, or for any block that represents a distinct operation. As a rule of thumb, if you find yourself copying more than a couple of lines, consider extracting a function.
DRY in Practice: A Small Case Study
Imagine a backup script that needs to compress a directory, then copy the archive to a remote server. Without functions, you might write the compression and copy commands twice for two different directories. With functions:
backup_dir() {
local dir="$1"
local archive="${dir}.tar.gz"
tar -czf "$archive" "$dir"
scp "$archive" user@server:/backups/
}
backup_dir /home/user/docs
backup_dir /var/wwwNow if you need to add a checksum or change the remote path, you update one function. This is a simple illustration, but it shows how functions reduce duplication and make the script more robust.
Frequently Asked Questions
Can I pass arguments to a bash function?
Yes, you can. Inside the function, $1, $2, etc. refer to the arguments passed when the function is called. For example, myfunc arg1 arg2 makes $1 equal to arg1 and $2 equal to arg2. You can also use $@ to get all arguments at once.
How do I return a string from a bash function?
Bash functions cannot return strings directly; they can only return an exit status (0-255). To return a string, you can use command substitution: result=$(myfunc). The function prints the string to stdout, and the substitution captures it. Alternatively, you can set a global variable as a side effect, but that is less clean.
What is the difference between a function and a script?
A function runs in the current shell, so it can change variables and the working directory that persist after the function ends. A script runs in a separate subshell, so its changes are lost when the script exits. Functions are also faster to call because there is no process creation overhead.
Can I define a function inside another function?
Yes, you can define a function inside another function. However, the inner function is only defined when the outer function is executed. This can be useful for creating closures, but it is rarely needed in bash. In most cases, it is clearer to define all functions at the top level of the script.
How do I make a function available to all my scripts?
Place the function definitions in a separate file, e.g., ~/.bash_functions, and source that file in your scripts with source ~/.bash_functions or . ~/.bash_functions. You can also add the source line to your ~/.bashrc to make the functions available in every interactive shell.