Skip to content

Latest commit

 

History

History
490 lines (348 loc) · 16.6 KB

getting-started.md

File metadata and controls

490 lines (348 loc) · 16.6 KB

Getting Started

This guide will help you get started with bash-logger quickly.

Table of Contents

Workflows

The repository includes GitHub Actions workflows to ensure code quality and consistency.

Linting Workflows

  • Lint Bash Scripts: Applies ShellCheck linting for all bash scripts in pull requests destined for the main branch.
  • Lint Markdown Files: Applies MarkdownLint for all markdown files in pull requests destined for the main branch.

Maintenance Workflows

  • Update License Year: Runs at 03:00 UTC on 1 January and can be started manually. It extends the copyright notice in LICENSE (2026 becomes 2026-2027, then 2026-2028, and so on) and opens a pull request with the change. The logic lives in scripts/update-license-year.sh.
  • Next Steps

Installation

bash-logger can be installed in several ways. Choose the method that best fits your needs.

Common Installation Locations

  • /usr/local/lib/bash-logger/logging.sh - System-wide installation
  • $HOME/.local/lib/bash-logger/logging.sh - User-specific installation
  • Project directory - Alongside your script

Note

The library runs in bash, zsh, dash and busybox ash, but the install script and bpkg need bash. On a system without bash, such as a default Alpine image, use Manual Installation. Upgrading from 2.x? See Upgrading to 3.0.

Using the Install Script

The easiest way to install bash-logger is with the provided installation script. It handles downloading the latest release, verifying integrity via SHA256 checksum, and setting up the module for you.

Quick Install (User):

curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh | bash

System-wide Installation (requires sudo):

curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh | sudo bash -s -- --system

Custom Location:

curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh | bash -s -- --prefix ~/tools

Additional Options:

  • --user - Install for current user only (default)
  • --system - Install system-wide (requires root)
  • --prefix PATH - Custom installation prefix
  • --auto-rc - Automatically add source line to shell RC file
  • --no-backup - Skip backing up existing installation
  • --skip-verify - Skip SHA256 checksum verification (not recommended)

Automatic Checksum Verification:

The install script automatically verifies the integrity of downloaded files using SHA256 checksums. This helps ensure the files haven't been corrupted or tampered with during download.

  • The script requires either sha256sum (Linux) or shasum (macOS) to be available
  • If a checksum tool isn't available, you'll be prompted to confirm whether to continue without verification
  • If verification fails, the installation is aborted to protect your system
  • For system-wide installations (--system), verification is strongly recommended

To skip verification (not recommended), use the --skip-verify flag:

curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh | bash -s -- --skip-verify

Installing a Specific Version:

To install a specific version instead of the latest release, set the INSTALL_VERSION environment variable to a valid release tag. Replace <version> with a tag from the releases page, such as 3.0.0. Only 3.x receives fixes (see SECURITY.md):

# Install a specific version (user installation)
INSTALL_VERSION=<version> bash -c "$(curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh)"

# Install a specific version (system-wide)
curl -fsSL https://raw.githubusercontent.com/GingerGraham/bash-logger/main/install.sh | sudo INSTALL_VERSION=<version> bash -s -- --system

For more details on available options, run the install script with the --help flag.

Manual Installation

If you prefer to install manually, simply place the logging.sh file in a directory of your choice. The module is a single, self-contained script that can be sourced from any location.

Example Installation

# System-wide (requires sudo)
sudo mkdir -p /usr/local/lib/bash-logger
sudo curl -o /usr/local/lib/bash-logger/logging.sh https://raw.githubusercontent.com/GingerGraham/bash-logger/main/logging.sh
sudo chmod 644 /usr/local/lib/bash-logger/logging.sh

# User-specific
mkdir -p ~/.local/lib/bash-logger
curl -o ~/.local/lib/bash-logger/logging.sh https://raw.githubusercontent.com/GingerGraham/bash-logger/main/logging.sh
chmod 644 ~/.local/lib/bash-logger/logging.sh

# Project directory
curl -o ./logging.sh https://raw.githubusercontent.com/GingerGraham/bash-logger/main/logging.sh
chmod 644 ./logging.sh

Installing from a Tagged Release

If you prefer to use a specific stable release version instead of the main branch, you can download directly from GitHub releases:

# Get the latest release version
LATEST_VERSION=$(curl -s https://api.github.com/repos/GingerGraham/bash-logger/releases/latest | grep -o '"tag_name": "[^"]*' | cut -d'"' -f4)

echo "Latest version: $LATEST_VERSION"

# Download the logging.sh file from the release
curl -L -o logging.sh "https://github.com/GingerGraham/bash-logger/releases/download/${LATEST_VERSION}/logging.sh"
chmod 644 logging.sh

This approach ensures you're using a stable, tagged release rather than the development version. The GitHub releases page at bash-logger releases shows all available versions and their release notes.

Verifying the Download with SHA256

It's recommended to verify the integrity of downloaded files using SHA256 checksums. Here's how to do it on different platforms:

Linux:

# Download the checksum file
curl -L -o logging.sh.sha256 "https://github.com/GingerGraham/bash-logger/releases/download/${LATEST_VERSION}/logging.sh.sha256"

# Verify the file
sha256sum -c logging.sh.sha256

Expected output on success:

logging.sh: OK

macOS:

# Download the checksum file
curl -L -o logging.sh.sha256 "https://github.com/GingerGraham/bash-logger/releases/download/${LATEST_VERSION}/logging.sh.sha256"

# Verify the file (macOS uses shasum)
shasum -a 256 -c logging.sh.sha256

Expected output on success:

logging.sh: OK

Windows (PowerShell):

# Get the latest release version
$releases = Invoke-WebRequest -Uri "https://api.github.com/repos/GingerGraham/bash-logger/releases/latest" | ConvertFrom-Json
$LATEST_VERSION = $releases.tag_name

# Download the logging.sh file
Invoke-WebRequest -Uri "https://github.com/GingerGraham/bash-logger/releases/download/$LATEST_VERSION/logging.sh" -OutFile "logging.sh"

# Download the checksum file
Invoke-WebRequest -Uri "https://github.com/GingerGraham/bash-logger/releases/download/$LATEST_VERSION/logging.sh.sha256" -OutFile "logging.sh.sha256"

# Read the expected checksum from the file
$expectedChecksum = (Get-Content logging.sh.sha256).Split()[0].ToLower()

# Calculate the actual checksum
$actualChecksum = (Get-FileHash -Path logging.sh -Algorithm SHA256).Hash.ToLower()

# Compare checksums
if ($expectedChecksum -eq $actualChecksum) {
    Write-Host "✓ Checksum verified successfully!" -ForegroundColor Green
} else {
    Write-Host "✗ Checksum mismatch! File may be corrupted or tampered with." -ForegroundColor Red
    exit 1
}

Manual Verification (All Platforms):

If you prefer to manually compare checksums:

  1. Download logging.sh.sha256 from the releases page
  2. Open the file and note the checksum value (first 64 characters)
  3. Calculate your file's checksum:
    • Linux/macOS: sha256sum logging.sh or shasum -a 256 logging.sh
    • Windows (PowerShell): (Get-FileHash -Path logging.sh -Algorithm SHA256).Hash
  4. Compare the two values - they should match exactly

Install with bpkg

For users of the bpkg package manager, bash-logger can be easily installed and managed.

For a consistent experience the configuration for bpkg is set to always use the global installation option. As such, the installation location will be: ${HOME}/.local/lib/bash-logger/logging.sh.

# Install the package
bpkg install GingerGraham/bash-logger@main

# Source in your script
source ${HOME}/.local/lib/bash-logger/logging.sh
init_logger
log_info "Installed via bpkg!"

Note: the @main branch reference is required as bpkg defaults to looking for the master branch, which does not exist in this repository.

Update an existing installation:

bpkg update bash-logger

bpkg does not support true, system-wide, global installations (i.e. /usr/local/lib), so the recommendation for these scenarios is to use the standard installation method described above, allowing users to determine the best location for their system.

Install with workbench

workbench (wb) can install bash-logger and keep it up to date. workbench-core must already be installed on the machine. bash-logger is not in workbench's built-in module catalog, so pass the repository URL:

wb add bash-logger https://github.com/GingerGraham/bash-logger.git

This installs logging.sh to ${HOME}/.local/lib/bash-logger/logging.sh, the same path used by the user-level install script and bpkg.

workbench always keeps this file in step with the tracked version. Do not edit it in place: a locally edited copy is backed up to ~/.local/share/workbench/backups/ and replaced on the next sync.

# Follow tagged releases only
wb track bash-logger --latest

# Update now
wb update bash-logger

# Stop managing bash-logger (the installed file is left in place)
wb remove bash-logger

Choosing one installation method

Use one installation method per user on each machine. The install script, bpkg and workbench all write to ${HOME}/.local/lib/bash-logger/logging.sh for user-level installs, and each manages that path independently.

If you use more than one, they replace each other's copy:

  • workbench treats a file it did not install as foreign, backs it up, and replaces it with the tracked version.
  • install.sh and bpkg update overwrite whatever is at that path with their own copy.
  • The next workbench sync sees that the file has changed, backs it up again, and replaces it again.

Scripts that source the library keep working, but the installed version can change unexpectedly and backups accumulate.

To switch from workbench to another method, run wb remove bash-logger first, then install with the other method. To switch to workbench, run wb add and it will back up the existing file and take over the path.

Basic Usage

The simplest way to use the logging module:

#!/bin/bash

# Source the logging module
source /path/to/logging.sh

# Initialize the logger with defaults
init_logger

# Log messages at different levels
log_debug "This is a debug message"
log_info "This is an info message"
log_warn "This is a warning message"
log_error "This is an error message"
log_fatal "This is a fatal error message"

Your First Script

Create a file called hello_logging.sh:

#!/bin/bash

# Source the logging module
source ./logging.sh

# Initialize with default settings
init_logger

# Log some messages
log_info "Hello, logging!"
log_info "The current date is: $(date)"
log_debug "This debug message won't appear (log level is INFO by default)"

# Enable verbose mode to see debug messages
log_info "Enabling debug mode..."
set_log_level DEBUG

log_debug "Now you can see debug messages!"
log_info "Script completed successfully"

To use the same script in a POSIX sh script (dash, busybox ash, or /bin/sh on Debian, Ubuntu and Alpine), start it with #!/bin/sh and source the library with ., because source is not available in every sh. The library calls are the same. See Shell Compatibility for the supported shells.

#!/bin/sh

# Source the logging module
. ./logging.sh

# Initialize with default settings
init_logger

log_info "Hello, logging!"
log_debug "This debug message won't appear (log level is INFO by default)"

set_log_level DEBUG
log_debug "Now you can see debug messages!"

Run it:

chmod +x hello_logging.sh
./hello_logging.sh

Common Options

Enable Verbose Output

# Show all messages including debug
init_logger --verbose

Log to a File

# Log to file in addition to console
init_logger --log "/tmp/myapp.log"

A log file that init_logger creates is readable and writable only by its owner (mode 600), and so is any directory it creates for it. To let a group read it, create the file first with the mode you want, or change the mode afterwards. See Log File Security.

Quiet Mode

# Only log to file, no console output
init_logger --log "/var/log/myapp.log" --quiet

Custom Log Level

# Set specific log level
init_logger --level WARN  # Only show WARN and above

Unsafe Newlines (Not Recommended)

By default, bash-logger sanitizes newline, carriage return, and tab characters to prevent log injection. Only enable unsafe mode if you fully control all log inputs.

# Allow newlines in log messages (unsafe)
init_logger --unsafe-allow-newlines

Quick Reference

Logging Functions

Function Level Default Visibility When to Use
log_debug DEBUG Hidden Detailed debugging information
log_info INFO Shown General informational messages
log_notice NOTICE Shown Normal but significant events
log_warn WARN Shown Warning messages
log_error ERROR Shown Error conditions
log_critical CRITICAL Shown Critical conditions
log_alert ALERT Shown Action must be taken immediately
log_emergency EMERGENCY Shown System is unusable
log_sensitive - Shown (console only) Sensitive data (console only)

Common Initialization Patterns

# Default behavior
init_logger

# Development/debugging
init_logger --verbose --color

# Production with file logging
init_logger --log "/var/log/myapp.log" --level INFO

# System service with journal
init_logger --journal --tag "myapp" --level INFO

# Configuration file
init_logger --config /etc/myapp/logging.conf

Exit Codes

The init_logger function returns:

  • 0 - Successful initialization
  • 1 - Error (e.g., unable to create log file)

Example error handling:

if ! init_logger --log "/var/log/myapp.log"; then
    echo "Failed to initialize logger" >&2
    exit 1
fi

Next Steps