π Functions β Core Customization Technique in Bash
π― What You Will Learnβ
- Understand what functions are in Bash and how they differ from aliases.
- Learn how to define, use, and persist functions for automation.
- Explore function scopes, arguments, and return values.
- Locate where function definitions are stored β in user-level and system-level files (with tree view).
- Implement real WordPress VPS functions for maintenance, backup, and service control.
- Follow best practices for organization, testing, and reliability.
1. What is a Bash Functionβ
A function in Bash is a named group of commands that can be executed as a unit. It allows reusable logic, parameter handling, and condition checks β far more flexible than an alias. Basic syntax:
function_name () {
commands
}
or:
function function_name {
commands
}
Example:
greet() {
echo "Hello, $(whoami)!"
}
When you type greet, the shell executes the block inside the braces.β
2. Why Functions Are Importantβ
| Purpose | Description |
| Automation | Combines multiple tasks into one reusable command. |
| Parameterization | Accepts arguments for flexible command execution. |
| Maintainability | Keeps scripts and repetitive commands organized. |
| Consistency | Defines standard logic across multiple WordPress servers. |
| Logic Handling | Supports conditionals (if, for, while) unlike aliases. |
3. Where Functions Are Storedβ
Functions can be defined temporarily in a shell session or persistently in configuration files.
| Scope | File | Applies To | Loaded When |
| User-level | ~/.bashrc or ~/.bash_functions | One user | On every interactive shell start |
| System-wide | /etc/profile.d/*.sh or /etc/bash.bashrc | All users | On every login or interactive session |
Directory Structure (Tree View)β
User-level configuration
/home/
βββ donnyariw/
βββ .bashrc
βββ .bash_functions
βββ .bash_aliases
βββ .bash_profile
βββ scripts/
βββ wpbackup.sh
System-wide configuration
/etc/
βββ profile
βββ bash.bashrc
βββ profile.d/
βββ lang.sh
βββ vim.sh
βββ custom-functions.sh
Each file type plays a specific role:
~/.bash_functionsβ custom user functions./etc/profile.d/custom-functions.shβ global functions for all users.
4. Function vs Aliasβ
| Feature | Alias | Function |
| Purpose | Command shortcut | Full logic routine |
| Can take arguments | β No | β Yes |
| Supports logic (if, loop) | β No | β Yes |
| Defined in | .bashrc, .bash_aliases | .bashrc, .bash_functions, /etc/profile.d/ |
| Used for | Simple shortcuts | Multi-step or parameterized automation |
Example comparison:
# Alias
alias wpstatus='wp plugin list --allow-root'
# Function
wpstatus() {
site=$1
wp plugin list --allow-root --path=/home/$site/public_html
}
Usage:
wpstatus dev-wpstrategist
5. Defining Functionsβ
a. Basic Functionβ
sayhello() {
echo "Hello from Bash!"
}
Usage:
sayhello
Output:
Hello from Bash!
b. Function with Argumentβ
greet() {
echo "Hello, $1!"
}
Usage:
greet Donny
Output:
Hello, Donny!
c. Return Valuesβ
checkfile() {
if [ -f "$1" ]; then
echo "File exists: $1"
return 0
else
echo "File not found."
return 1
fi
}
Usage:
checkfile /etc/passwd
echo $?
6. Persistent Function Storageβ
a. User-Level Persistent Functionsβ
Inside ~/.bashrc or ~/.bash_functions:
wpbackupsite() {
site=$1
wp db export /root/wpbackup/${site}-$(date +%F).sql \
--path=/home/$site/public_html --allow-root
}
Then reload:
source ~/.bashrc
Now:
wpbackupsite dev-wpstrategist
b. System-Wide Persistent Functionsβ
Create a file inside /etc/profile.d/:
sudo nano /etc/profile.d/custom-functions.sh
Example content:
# /etc/profile.d/custom-functions.sh
restartservices() {
echo "Restarting Redis, PHP, and LiteSpeed..."
systemctl restart redis
systemctl restart lsws
echo "Services restarted successfully."
}
Make executable:
chmod +x /etc/profile.d/custom-functions.sh
All users can now use:
restartservices
7. WordPress VPS Practical Use Casesβ
| Function Name | Example Definition | Description |
wpbackupsite | wp db export /root/wpbackup/... | Backup per WordPress site |
wpupdateall | Loops over /home/*/*/public_html | Updates plugins across all sites |
redisflush | redis-cli flushall | Clears Redis cache |
restartservices | Restart PHP, Redis, LiteSpeed | Reloads services efficiently |
wpcleancache | Delete LSCache + Redis flush | Clears both caching layers |
Example 1: Backup Functionβ
wpbackupsite() {
site=$1
if [ -d "/home/$site/public_html" ]; then
echo "Backing up $site..."
wp db export /root/wpbackup/${site}-$(date +%F).sql \
--path=/home/$site/public_html --allow-root
echo "Backup complete."
else
echo "Error: $site not found!"
fi
}
Example 2: Global Plugin Updaterβ
wpupdateall() {
for dir in /home/*/*/public_html; do
if [ -f "$dir/wp-config.php" ]; then
echo "β Updating plugins in $dir"
wp plugin update --all --path="$dir" --allow-root
fi
done
echo "All WordPress sites updated."
}
Example 3: Combined Cache Cleanerβ
wpcleancache() {
echo "Flushing Redis cache..."
redis-cli flushall
echo "Clearing LSCache..."
rm -rf /home/*/*/public_html/wp-content/lscache/*
echo "Cache cleared."
}
8. Organizing Functionsβ
To maintain structure:
- Create a dedicated file:
touch ~/.bash_functions
- Add your functions there.
- Load them automatically from
.bashrc:
if [ -f ~/.bash_functions ]; then
source ~/.bash_functions
fi
Example Tree View of Integrationβ
/home/donnyariw/
βββ .bashrc
βββ .bash_functions
βββ .bash_aliases
Flow of execution:
bash startup β .bashrc β .bash_functions β functions available globally
9. Best Practicesβ
- Use descriptive names:
wpbackupsiteis clearer thanbkpwp. - Validate input: Always check if
$1or files exist. - Use absolute paths: Prevents dependency on environment variables.
- Return proper exit codes: Use
return 0(success) orreturn 1(failure). - Keep logic short: For long tasks, place them in scripts under
/root/scripts/. - Avoid re-defining system commands: Use
commandkeyword to call the original binary. - Test in a sandbox first: Before deploying to production VPS.
10. Troubleshootingβ
| Problem | Cause | Fix |
| Function not found | File not sourced | Run source ~/.bashrc or restart terminal |
| Wrong directory reference | $1 undefined | Use argument validation (if [ -z "$1" ]; then) |
| Command error | Missing absolute path | Use /usr/bin/wp, /usr/bin/systemctl, etc. |
| Function overrides | Duplicate name | Rename or unset -f function_name |
11. Quick Labβ
Objective: Automate backups and plugin updates for all WordPress sites.
- Open your function file:
nano ~/.bash_functions
- Add:
wpbackupsite() {
site=$1
wp db export /root/wpbackup/${site}-$(date +%F).sql \
--path=/home/$site/public_html --allow-root
}
wpupdateall() {
for dir in /home/*/*/public_html; do
if [ -f "$dir/wp-config.php" ]; then
echo "Updating: $dir"
wp plugin update --all --path="$dir" --allow-root
fi
done
}
- Load functions:
source ~/.bash_functions
- Test:
wpbackupsite dev-wpstrategist
wpupdateall
Expected output:
Backing up dev-wpstrategist...
β Updating plugins in /home/dev-wpstrategist/public_html
All WordPress sites updated.
12. Glossaryβ
| Term | Definition |
| Function | A reusable Bash code block that executes multiple commands. |
| Positional Parameter | $1, $2, etc., arguments passed to a function. |
| Return Code | Numeric result of function execution (0=success). |
| Sourcing | Executing the contents of a file in the current shell. |
| Scope | Visibility of functions or variables within the environment. |
13. Mini-Quizβ
- Where are user-level Bash functions typically stored?
- Which command makes your new function available immediately?
- How do you pass arguments to a function?
- Whatβs the main advantage of a function over an alias?
- Which directory is best for defining global (system-wide) functions?
14. Summaryβ
- Functions are reusable automation blocks in Bash β more powerful than aliases.
- They accept parameters, can include loops, and return exit codes.
- User functions belong in
~/.bash_functionsor~/.bashrc; global ones in/etc/profile.d/*.sh. - Ideal for WordPress VPS automation such as backups, cache clearing, or updates.
- Keep them modular, descriptive, and validated for safe and predictable automation.
- Always maintain clear documentation and backup before deploying on production systems.
Would you like me to continue next with βCore Customization Technique: Environment Variablesβ (next in your curriculum sequence), including file location mapping and VPS examples?
About function. how to call and check all function that is registered in terminal? for alias we can simply type alias
Excellent question β this shows youβre diving into the declarative layer of Bash configuration.
Letβs break it down step-by-step, just like we did with aliases, and clarify how to list, inspect, and call functions inside your Bash terminal.β
1. How to Call (Run) a Bash Functionβ
Once a function is defined (either interactively or via your .bashrc / .bash_functions),
you call it just like a regular command:
function_name
Example:
greet() {
echo "Hello, $(whoami)!"
}
Then call it:
greet
Output:
Hello, root!
If your function accepts parameters:
wpbackupsite dev-wpstrategist
(where $1 inside the function receives dev-wpstrategist).β
π 2. How to List All Registered Functionsβ
Unlike aliases (where you type alias),
Bash functions can be listed with the following commands:
| Command | Description |
declare -F | Lists only the names of currently defined functions. |
declare -f | Lists all functions with their full body definitions. |
typeset -F | Same as declare -F (POSIX-compliant equivalent). |
compgen -A function | Lists function names (useful in scripts). |
Examplesβ
a. List function names only
declare -F
Output:
declare -f wpbackupsite
declare -f wpupdateall
declare -f restartservices
b. List function bodies
declare -f
Output:
wpbackupsite ()
{
site=$1
wp db export /root/wpbackup/${site}-$(date +%F).sql --path=/home/$site/public_html --allow-root
}
c. Quick names only (clean output)
compgen -A function
Output:
wpbackupsite
wpupdateall
restartservices
π 3. How to Check a Specific Function Definitionβ
To see what a specific function does:
declare -f function_name
Example:
declare -f wpbackupsite
Output:
wpbackupsite ()
{
site=$1
wp db export /root/wpbackup/${site}-$(date +%F).sql --path=/home/$site/public_html --allow-root
}
This is the functionβs βsource codeβ β useful for debugging or verifying changes.β
π§ 4. How to Check if a Function Existsβ
Use:
type function_name
Example:
type wpbackupsite
Output:
wpbackupsite is a function
wpbackupsite ()
{
site=$1
wp db export /root/wpbackup/${site}-$(date +%F).sql --path=/home/$site/public_html --allow-root
}
βοΈ 5. How to Remove a Function from Memoryβ
If youβve redefined or no longer need a function:
unset -f function_name
Example:
unset -f wpbackupsite
Now check:
type wpbackupsite
Output:
bash: type: wpbackupsite: not found
π§© 6. Useful Variationsβ
| Task | Command | Purpose |
| List all functions | declare -F | Shows all function names |
| Show all definitions | declare -f | Displays entire code body |
| Show one definition | declare -f wpbackupsite | Inspects one function |
| Search function by name | `declare -F | grep wp` |
| Check if exists | type wpupdateall | Returns info if defined |
| Remove function | unset -f wpupdateall | Deletes from session |
| Export function to subshell | export -f wpbackupsite | Makes available to child shells |
π§° 7. Practical Exampleβ
Letβs combine everything into a mini workflow.
# Define a function
wpcleancache() {
redis-cli flushall
rm -rf /home/*/*/public_html/wp-content/lscache/*
echo "Cache cleared for all sites!"
}
# Verify itβs registered
declare -F | grep wpcleancache
# Test the function
wpcleancache
# View the function code
declare -f wpcleancache
# Remove if no longer needed
unset -f wpcleancache
π§ 8. Summary Tableβ
| Purpose | Command |
| List all function names | declare -F or compgen -A function |
| List all functions with definitions | declare -f |
| Show specific function definition | declare -f function_name |
| Check if name refers to function | type function_name |
| Remove function | unset -f function_name |
| Export to subshell | export -f function_name |
| Execute a function | function_name [arguments] |
β Quick Recapβ
- To call a function β just type its name.
- To see all available functions β use
declare -F. - To inspect full definitions β use
declare -f. - To check specific function β
type function_name. - To remove a function β
unset -f function_name. - To make global (subshell) β
export -f function_name.