Skip to main content

πŸ“˜ Functions β€” Core Customization Technique in Bash


🎯 What You Will Learn​

  1. Understand what functions are in Bash and how they differ from aliases.
  2. Learn how to define, use, and persist functions for automation.
  3. Explore function scopes, arguments, and return values.
  4. Locate where function definitions are stored β€” in user-level and system-level files (with tree view).
  5. Implement real WordPress VPS functions for maintenance, backup, and service control.
  6. 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​

PurposeDescription
AutomationCombines multiple tasks into one reusable command.
ParameterizationAccepts arguments for flexible command execution.
MaintainabilityKeeps scripts and repetitive commands organized.
ConsistencyDefines standard logic across multiple WordPress servers.
Logic HandlingSupports 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.

ScopeFileApplies ToLoaded When
User-level~/.bashrc or ~/.bash_functionsOne userOn every interactive shell start
System-wide/etc/profile.d/*.sh or /etc/bash.bashrcAll usersOn 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​

FeatureAliasFunction
PurposeCommand shortcutFull 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 forSimple shortcutsMulti-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 NameExample DefinitionDescription
wpbackupsitewp db export /root/wpbackup/...Backup per WordPress site
wpupdateallLoops over /home/*/*/public_htmlUpdates plugins across all sites
redisflushredis-cli flushallClears Redis cache
restartservicesRestart PHP, Redis, LiteSpeedReloads services efficiently
wpcleancacheDelete LSCache + Redis flushClears 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:

  1. Create a dedicated file:
touch ~/.bash_functions

  1. Add your functions there.
  2. 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​

  1. Use descriptive names: wpbackupsite is clearer than bkpwp.
  2. Validate input: Always check if $1 or files exist.
  3. Use absolute paths: Prevents dependency on environment variables.
  4. Return proper exit codes: Use return 0 (success) or return 1 (failure).
  5. Keep logic short: For long tasks, place them in scripts under /root/scripts/.
  6. Avoid re-defining system commands: Use command keyword to call the original binary.
  7. Test in a sandbox first: Before deploying to production VPS.

10. Troubleshooting​

ProblemCauseFix
Function not foundFile not sourcedRun source ~/.bashrc or restart terminal
Wrong directory reference$1 undefinedUse argument validation (if [ -z "$1" ]; then)
Command errorMissing absolute pathUse /usr/bin/wp, /usr/bin/systemctl, etc.
Function overridesDuplicate nameRename or unset -f function_name

11. Quick Lab​

Objective: Automate backups and plugin updates for all WordPress sites.

  1. Open your function file:
nano ~/.bash_functions

  1. 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
}

  1. Load functions:
source ~/.bash_functions

  1. 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​

TermDefinition
FunctionA reusable Bash code block that executes multiple commands.
Positional Parameter$1, $2, etc., arguments passed to a function.
Return CodeNumeric result of function execution (0=success).
SourcingExecuting the contents of a file in the current shell.
ScopeVisibility of functions or variables within the environment.

13. Mini-Quiz​

  1. Where are user-level Bash functions typically stored?
  2. Which command makes your new function available immediately?
  3. How do you pass arguments to a function?
  4. What’s the main advantage of a function over an alias?
  5. 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_functions or ~/.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:

CommandDescription
declare -FLists only the names of currently defined functions.
declare -fLists all functions with their full body definitions.
typeset -FSame as declare -F (POSIX-compliant equivalent).
compgen -A functionLists 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​

TaskCommandPurpose
List all functionsdeclare -FShows all function names
Show all definitionsdeclare -fDisplays entire code body
Show one definitiondeclare -f wpbackupsiteInspects one function
Search function by name`declare -Fgrep wp`
Check if existstype wpupdateallReturns info if defined
Remove functionunset -f wpupdateallDeletes from session
Export function to subshellexport -f wpbackupsiteMakes 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​

PurposeCommand
List all function namesdeclare -F or compgen -A function
List all functions with definitionsdeclare -f
Show specific function definitiondeclare -f function_name
Check if name refers to functiontype function_name
Remove functionunset -f function_name
Export to subshellexport -f function_name
Execute a functionfunction_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.