23 KiB
core.func Functions Reference
Overview
This document provides a comprehensive alphabetical reference of all functions in core.func, including parameters, dependencies, usage examples, and error handling.
Function Categories
Initialization Functions
load_functions()
Purpose: Main function loader that initializes all core utilities Parameters: None Returns: None Side Effects:
- Sets
__FUNCTIONS_LOADED=1to prevent reloading - Calls all core function groups in sequence
- Initializes color, formatting, icons, defaults, and standard mode
Dependencies: None
Environment Variables Used:
__FUNCTIONS_LOADED
Usage Example:
# Automatically called when core.func is sourced
source core.func
# load_functions() is called automatically
Color and Formatting Functions
color()
Purpose: Set ANSI color codes for styled terminal output Parameters: None Returns: None Side Effects: Sets global color variables Dependencies: None Environment Variables Used: None
Sets Variables:
YW: YellowYWB: Bright yellowBL: BlueRD: RedBGN: Bright greenGN: GreenDGN: Dark greenCL: Clear/reset
Usage Example:
color
echo -e "${GN}Success message${CL}"
echo -e "${RD}Error message${CL}"
color_spinner()
Purpose: Set color codes specifically for spinner output Parameters: None Returns: None Side Effects: Sets spinner-specific color variables Dependencies: None Environment Variables Used: None
Sets Variables:
CS_YW: Yellow for spinnerCS_YWB: Bright yellow for spinnerCS_CL: Clear for spinner
formatting()
Purpose: Define formatting helpers for terminal output Parameters: None Returns: None Side Effects: Sets global formatting variables Dependencies: None Environment Variables Used: None
Sets Variables:
BFR: Back and forward resetBOLD: Bold textHOLD: Space characterTAB: Two spacesTAB3: Six spaces
Icon Functions
icons()
Purpose: Set symbolic icons used throughout user feedback and prompts
Parameters: None
Returns: None
Side Effects: Sets global icon variables
Dependencies: formatting() (for TAB variable)
Environment Variables Used: TAB, CL
Sets Variables:
CM: Check markCROSS: Cross markDNSOK: DNS successDNSFAIL: DNS failureINFO: Information iconOS: Operating system iconOSVERSION: OS version iconCONTAINERTYPE: Container type iconDISKSIZE: Disk size iconCPUCORE: CPU core iconRAMSIZE: RAM size iconSEARCH: Search iconVERBOSE_CROPPED: Verbose mode iconVERIFYPW: Password verification iconCONTAINERID: Container ID iconHOSTNAME: Hostname iconBRIDGE: Bridge iconNETWORK: Network iconGATEWAY: Gateway iconICON_DISABLEIPV6: IPv6 disable iconDEFAULT: Default settings iconMACADDRESS: MAC address iconVLANTAG: VLAN tag iconROOTSSH: SSH key iconCREATING: Creating iconADVANCED: Advanced settings iconFUSE: FUSE iconHOURGLASS: Hourglass icon
Default Variables Functions
default_vars()
Purpose: Set default retry and wait variables for system actions Parameters: None Returns: None Side Effects: Sets retry configuration variables Dependencies: None Environment Variables Used: None
Sets Variables:
RETRY_NUM: Number of retry attempts (default: 10)RETRY_EVERY: Seconds between retries (default: 3)i: Retry counter initialized to RETRY_NUM
set_std_mode()
Purpose: Set default verbose mode for script execution
Parameters: None
Returns: None
Side Effects: Sets STD variable based on VERBOSE setting
Dependencies: None
Environment Variables Used: VERBOSE
Sets Variables:
STD: "silent" if VERBOSE != "yes", empty string if VERBOSE = "yes"
Silent Execution Functions
silent()
Purpose: Execute commands silently with detailed error reporting
Parameters: $* - Command and arguments to execute
Returns: None (exits on error)
Side Effects:
- Executes command with output redirected to log file
- On error, displays detailed error information
- Exits with command's exit code
Dependencies:
error_handler.func(for error explanations) Environment Variables Used:SILENT_LOGFILE
Usage Example:
silent apt-get update
silent apt-get install -y package-name
Error Handling:
- Captures command output to
/tmp/silent.$$.log - Shows error code explanation
- Displays last 10 lines of log
- Provides command to view full log
System Check Functions
shell_check()
Purpose: Verify that the script is running in Bash shell Parameters: None Returns: None (exits if not Bash) Side Effects:
- Checks current shell process
- Exits with error message if not Bash Dependencies: None Environment Variables Used: None
Usage Example:
shell_check
# Script continues if Bash, exits if not
root_check()
Purpose: Ensure script is running as root user Parameters: None Returns: None (exits if not root) Side Effects:
- Checks user ID and parent process
- Exits with error message if not root Dependencies: None Environment Variables Used: None
Usage Example:
root_check
# Script continues if root, exits if not
pve_check()
Purpose: Verify Proxmox VE version compatibility Parameters: None Returns: None (exits if unsupported version) Side Effects:
- Checks PVE version using pveversion command
- Exits with error message if unsupported
Dependencies:
pveversioncommand Environment Variables Used: None
Supported Versions:
- Proxmox VE 8.0 - 8.9
- Proxmox VE 9.0 (only)
Usage Example:
pve_check
# Script continues if supported version, exits if not
arch_check()
Purpose: Verify system architecture is AMD64 Parameters: None Returns: None (exits if not AMD64) Side Effects:
- Checks system architecture
- Exits with PiMox warning if not AMD64
Dependencies:
dpkgcommand Environment Variables Used: None
Usage Example:
arch_check
# Script continues if AMD64, exits if not
ssh_check()
Purpose: Detect and warn about external SSH usage Parameters: None Returns: None Side Effects:
- Checks SSH_CLIENT environment variable
- Warns if connecting from external IP
- Allows local connections (127.0.0.1 or host IP)
Dependencies: None
Environment Variables Used:
SSH_CLIENT
Usage Example:
ssh_check
# Shows warning if external SSH, continues anyway
Header Management Functions
get_header()
Purpose: Download and cache application header files Parameters: None (uses APP and APP_TYPE variables) Returns: Header content on success, empty on failure Side Effects:
- Downloads header from remote URL
- Caches header locally
- Creates directory structure if needed
Dependencies:
curlcommand Environment Variables Used:APP,APP_TYPE
Usage Example:
export APP="plex"
export APP_TYPE="ct"
header_content=$(get_header)
header_info()
Purpose: Display application header information Parameters: None (uses APP variable) Returns: None Side Effects:
- Clears screen
- Displays header content
- Gets terminal width for formatting
Dependencies:
get_header(),tputcommand Environment Variables Used:APP
Usage Example:
export APP="plex"
header_info
# Displays Plex header information
Utility Functions
ensure_tput()
Purpose: Ensure tput command is available for terminal control Parameters: None Returns: None Side Effects:
- Installs ncurses package if tput missing
- Works on Alpine and Debian-based systems
Dependencies:
apkorapt-getpackage managers Environment Variables Used: None
Usage Example:
ensure_tput
# Installs ncurses if needed, continues if already available
is_alpine()
Purpose: Detect if running on Alpine Linux
Parameters: None
Returns: 0 if Alpine, 1 if not Alpine
Side Effects: None
Dependencies: None
Environment Variables Used: var_os, PCT_OSTYPE
Usage Example:
if is_alpine; then
echo "Running on Alpine Linux"
else
echo "Not running on Alpine Linux"
fi
is_verbose_mode()
Purpose: Check if verbose mode is enabled
Parameters: None
Returns: 0 if verbose mode, 1 if not verbose
Side Effects: None
Dependencies: None
Environment Variables Used: VERBOSE, var_verbose
Usage Example:
if is_verbose_mode; then
echo "Verbose mode enabled"
else
echo "Verbose mode disabled"
fi
fatal()
Purpose: Display fatal error and terminate script
Parameters: $1 - Error message
Returns: None (terminates script)
Side Effects:
- Displays error message
- Sends INT signal to current process
Dependencies:
msg_error()Environment Variables Used: None
Usage Example:
fatal "Critical error occurred"
# Script terminates after displaying error
Spinner Functions
spinner()
Purpose: Display animated spinner for progress indication Parameters: None (uses SPINNER_MSG variable) Returns: None (runs indefinitely) Side Effects:
- Displays rotating spinner characters
- Uses terminal control sequences
Dependencies:
color_spinner()Environment Variables Used:SPINNER_MSG
Usage Example:
SPINNER_MSG="Processing..."
spinner &
SPINNER_PID=$!
# Spinner runs in background
clear_line()
Purpose: Clear current terminal line
Parameters: None
Returns: None
Side Effects: Clears current line using terminal control
Dependencies: tput command
Environment Variables Used: None
stop_spinner()
Purpose: Stop running spinner and cleanup Parameters: None Returns: None Side Effects:
- Kills spinner process
- Removes PID file
- Resets terminal settings
- Unsets spinner variables
Dependencies: None
Environment Variables Used:
SPINNER_PID,SPINNER_MSG
Usage Example:
stop_spinner
# Stops spinner and cleans up
Message Functions
msg_info()
Purpose: Display informational message with spinner
Parameters: $1 - Message text
Returns: None
Side Effects:
- Starts spinner if not in verbose mode
- Tracks shown messages to prevent duplicates
- Displays message with hourglass icon in verbose mode
Dependencies:
spinner(),is_verbose_mode(),is_alpine()Environment Variables Used:MSG_INFO_SHOWN
Usage Example:
msg_info "Installing package..."
# Shows spinner with message
msg_ok()
Purpose: Display success message
Parameters: $1 - Success message text
Returns: None
Side Effects:
- Stops spinner
- Displays green checkmark with message
- Removes message from shown tracking
Dependencies:
stop_spinner()Environment Variables Used:MSG_INFO_SHOWN
Usage Example:
msg_ok "Package installed successfully"
# Shows green checkmark with message
msg_error()
Purpose: Display error message
Parameters: $1 - Error message text
Returns: None
Side Effects:
- Stops spinner
- Displays red cross with message
Dependencies:
stop_spinner()Environment Variables Used: None
Usage Example:
msg_error "Installation failed"
# Shows red cross with message
msg_warn()
Purpose: Display warning message
Parameters: $1 - Warning message text
Returns: None
Side Effects:
- Stops spinner
- Displays yellow info icon with message
Dependencies:
stop_spinner()Environment Variables Used: None
Usage Example:
msg_warn "This operation may take some time"
# Shows yellow info icon with message
msg_custom()
Purpose: Display custom message with specified symbol and color Parameters:
$1- Custom symbol (default: "[*]")$2- Color code (default: "\e[36m")$3- Message text Returns: None Side Effects:- Stops spinner
- Displays custom formatted message
Dependencies:
stop_spinner()Environment Variables Used: None
Usage Example:
msg_custom "⚡" "\e[33m" "Custom warning message"
# Shows custom symbol and color with message
msg_debug()
Purpose: Display debug message if debug mode enabled
Parameters: $* - Debug message text
Returns: None
Side Effects:
- Only displays if var_full_verbose is set
- Shows timestamp and debug prefix
Dependencies: None
Environment Variables Used:
var_full_verbose,var_verbose
Usage Example:
export var_full_verbose=1
msg_debug "Debug information here"
# Shows debug message with timestamp
System Management Functions
check_or_create_swap()
Purpose: Check for active swap and optionally create swap file Parameters: None Returns: 0 if swap exists or created, 1 if skipped Side Effects:
- Checks for active swap
- Prompts user to create swap if none found
- Creates swap file if user confirms
Dependencies:
swapon,dd,mkswapcommands Environment Variables Used: None
Usage Example:
if check_or_create_swap; then
echo "Swap is available"
else
echo "No swap available"
fi
Function Call Hierarchy
Initialization Flow
load_functions()
├── color()
├── formatting()
├── icons()
├── default_vars()
└── set_std_mode()
Message System Flow
msg_info()
├── is_verbose_mode()
├── is_alpine()
├── spinner()
└── color_spinner()
msg_ok()
├── stop_spinner()
└── clear_line()
msg_error()
└── stop_spinner()
msg_warn()
└── stop_spinner()
System Check Flow
pve_check()
├── pveversion command
└── version parsing
arch_check()
├── dpkg command
└── architecture check
shell_check()
├── ps command
└── shell detection
root_check()
├── id command
└── parent process check
Silent Execution Flow
silent()
├── Command execution
├── Output redirection
├── Error handling
├── error_handler.func loading
└── Log management
Error Handling Patterns
System Check Errors
- All system check functions exit with appropriate error messages
- Clear indication of what's wrong and how to fix it
- Graceful exit with sleep delay for user to read message
Silent Execution Errors
- Commands executed via
silent()capture output to log file - On failure, displays error code explanation
- Shows last 10 lines of log output
- Provides command to view full log
Spinner Errors
- Spinner functions handle process cleanup on exit
- Trap handlers ensure spinners are stopped
- Terminal settings are restored on error
Environment Variable Dependencies
Required Variables
APP: Application name for header displayAPP_TYPE: Application type (ct/vm) for header pathsVERBOSE: Verbose mode setting
Optional Variables
var_os: OS type for Alpine detectionPCT_OSTYPE: Alternative OS type variablevar_verbose: Alternative verbose settingvar_full_verbose: Debug mode setting
Internal Variables
_CORE_FUNC_LOADED: Prevents multiple loading__FUNCTIONS_LOADED: Prevents multiple function loadingSILENT_LOGFILE: Silent execution log file pathSPINNER_PID: Spinner process IDSPINNER_MSG: Spinner message textMSG_INFO_SHOWN: Tracks shown info messages-PHS_SILENT: Unattended mode flag (1 = silent)var_unattended: Unattended mode variable (yes/no)UNATTENDED: Alternative unattended mode variable
Unattended/Interactive Prompt Functions
These functions provide a unified way to handle user prompts in both interactive and unattended modes. They automatically detect the execution context and either prompt the user (with timeout) or use default values silently.
is_unattended()
Purpose: Detect if script is running in unattended/silent mode Parameters: None Returns:
0(true): Running unattended1(false): Running interactively Side Effects: None Dependencies: None Environment Variables Used:PHS_SILENT,var_unattended,UNATTENDED
Usage Example:
if is_unattended; then
echo "Running in unattended mode"
else
echo "Running interactively"
fi
prompt_confirm()
Purpose: Prompt user for yes/no confirmation with timeout and unattended support Parameters:
$1- Prompt message (required)$2- Default value: "y" or "n" (optional, default: "n")$3- Timeout in seconds (optional, default: 60) Returns:0: User confirmed (yes)1: User declined (no) or timeout with default "n" Side Effects: Displays prompt to terminal Dependencies:is_unattended()Environment Variables Used: Color variables (YW,CL)
Behavior:
- Unattended mode: Immediately returns default value
- Non-TTY: Immediately returns default value
- Interactive: Displays prompt with timeout countdown
- Timeout: Auto-applies default value after specified seconds
Usage Examples:
# Basic confirmation (default: no)
if prompt_confirm "Proceed with installation?"; then
install_package
fi
# Default to yes, 30 second timeout
if prompt_confirm "Continue?" "y" 30; then
continue_operation
fi
# In unattended mode (will use default immediately)
var_unattended=yes
prompt_confirm "Delete files?" "n" && echo "Deleting" || echo "Skipped"
prompt_input()
Purpose: Prompt user for text input with timeout and unattended support Parameters:
$1- Prompt message (required)$2- Default value (optional, default: "")$3- Timeout in seconds (optional, default: 60) Output: Prints the user input or default value to stdout Returns:0always Side Effects: Displays prompt to stderr (keeps stdout clean for value) Dependencies:is_unattended()Environment Variables Used: Color variables (YW,CL)
Behavior:
- Unattended mode: Returns default value immediately
- Non-TTY: Returns default value immediately
- Interactive: Waits for user input with timeout
- Empty input: Returns default value
- Timeout: Returns default value
Usage Examples:
# Get username with default
username=$(prompt_input "Enter username:" "admin" 30)
echo "Using username: $username"
# With validation loop
while true; do
port=$(prompt_input "Enter port:" "8080" 30)
[[ "$port" =~ ^[0-9]+$ ]] && break
echo "Invalid port number"
done
# Capture value in unattended mode
var_unattended=yes
db_name=$(prompt_input "Database name:" "myapp_db")
prompt_select()
Purpose: Prompt user to select from a list of options with timeout support Parameters:
$1- Prompt message (required)$2- Default option number, 1-based (optional, default: 1)$3- Timeout in seconds (optional, default: 60)$4+- Options to display (required, at least 1) Output: Prints the selected option value to stdout Returns:0: Success1: No options provided Side Effects: Displays numbered menu to stderr Dependencies:is_unattended()Environment Variables Used: Color variables (YW,GN,CL)
Behavior:
- Unattended mode: Returns default selection immediately
- Non-TTY: Returns default selection immediately
- Interactive: Displays numbered menu with timeout
- Invalid selection: Uses default
- Timeout: Auto-selects default
Usage Examples:
# Simple selection
choice=$(prompt_select "Select database:" 1 30 "PostgreSQL" "MySQL" "SQLite")
echo "Selected: $choice"
# Using array
options=("Production" "Staging" "Development")
env=$(prompt_select "Select environment:" 2 60 "${options[@]}")
# In automation scripts
var_unattended=yes
db=$(prompt_select "Database:" 1 30 "postgres" "mysql" "sqlite")
# Returns "postgres" immediately without menu
prompt_password()
Purpose: Prompt user for password input with hidden characters and auto-generation Parameters:
$1- Prompt message (required)$2- Default value or "generate" for auto-generation (optional)$3- Timeout in seconds (optional, default: 60)$4- Minimum length for validation (optional, default: 0) Output: Prints the password to stdout Returns:0always Side Effects: Displays prompt to stderr with hidden input Dependencies:is_unattended(),openssl(for generation) Environment Variables Used: Color variables (YW,CL)
Behavior:
- "generate" default: Creates random 16-character password
- Unattended mode: Returns default/generated password immediately
- Non-TTY: Returns default/generated password immediately
- Interactive: Hidden input with timeout
- Min length validation: Falls back to default if too short
- Timeout: Returns default/generated password
Usage Examples:
# Auto-generate password if user doesn't provide one
password=$(prompt_password "Enter password:" "generate" 30)
echo "Password has been set"
# Require minimum length
db_pass=$(prompt_password "Database password:" "" 60 12)
# With default password
admin_pass=$(prompt_password "Admin password:" "changeme123" 30)
# In unattended mode with auto-generation
var_unattended=yes
password=$(prompt_password "Password:" "generate")
# Returns randomly generated password
Prompt Function Decision Flow
prompt_confirm() / prompt_input() / prompt_select() / prompt_password()
│
├── is_unattended()? ─────────────────────┐
│ └── PHS_SILENT=1? │
│ └── var_unattended=yes? ├── YES → Return default immediately
│ └── UNATTENDED=yes? │
│ │
├── TTY available? ─────────────── NO ────┘
│
└── Interactive Mode
├── Display prompt with timeout hint
├── read -t $timeout
│ ├── User input received → Validate and return
│ ├── Empty input → Return default
│ └── Timeout → Return default with message
└── Return value
Migration Guide: Converting read Commands
To make existing scripts unattended-compatible, replace read commands with the appropriate prompt function:
Before (blocking):
read -rp "Continue? [y/N]: " confirm
[[ "$confirm" =~ ^[Yy]$ ]] && do_something
read -p "Enter port: " port
port="${port:-8080}"
read -p "Select (1-3): " choice
After (unattended-safe):
prompt_confirm "Continue?" "n" && do_something
port=$(prompt_input "Enter port:" "8080")
choice=$(prompt_select "Select option:" 1 60 "Option 1" "Option 2" "Option 3")