Skip to content

string.sh

Eugene Lazutkin edited this page Mar 20, 2026 · 1 revision

string.sh

String utilities: padding, cleaning, length calculation, and terminal-aware output.

This is the lowest-level module in the library. It has no dependencies and is loaded automatically by box.sh.

Bash requirement: 4.0+

Usage

source "/path/to/options.bash/string.sh"

Functions

string::clean STRING

Strip ANSI escape codes from a string. If ansi::strip is available (i.e., an ANSI module has been loaded), it delegates to that function. Otherwise, returns the string unchanged.

source ansi.sh
source string.sh

string::clean "${RED}hello${RESET_ALL}"
# Output: hello

string::length STRING

Return the visible length of a string (after stripping ANSI codes). Delegates to ansi::length if available, otherwise returns ${#string}.

string::length "${RED}hello${RESET_ALL}"
# Output: 5

string::make_pad LENGTH [CHAR]

Create a padding string of the given length filled with CHAR (default: space).

string::make_pad 5
# Output: "     " (5 spaces)

string::make_pad 3 "."
# Output: "..."

The pad character is validated through string::clean — it must be exactly one visible character (but may contain ANSI codes).

string::pad STRING LENGTH [ALIGN] [CHAR]

Pad a string to the given visible length. Alignment options:

Value Alias Effect
left l Pad on the right (default)
right r Pad on the left
center c Pad both sides (extra goes right)
string::pad "hi" 10 left
# Output: "hi        "

string::pad "hi" 10 right "."
# Output: "........hi"

string::pad "hi" 10 center
# Output: "    hi    "

ANSI-aware: the visible length is computed after stripping escape codes, so styled strings are padded correctly.

string::out ARGS...

Terminal-aware echo -e. When stdout is a terminal (or $TERM is unset), output includes ANSI codes. When piped to a file or another command, ANSI codes are stripped automatically.

string::out "${RED}Error:${RESET_ALL} something broke"
# Terminal: colored output
# Piped:   "Error: something broke"

Returns 0.

string::err ARGS...

Like string::out, but writes to stderr. Always returns 1 — designed for error reporting where the return code signals failure.

string::err "${RED}Error:${RESET_ALL} file not found" || true
# Writes to stderr, returns 1

Notes

  • string::clean and string::length are ANSI-aware only when an ANSI module (ansi.sh or ansi-tput.sh) has been loaded. Without it, they treat the raw string as-is.
  • The terminal detection check is [[ -t 1 || -z "$TERM" ]] for stdout and [[ -t 2 || -z "$TERM" ]] for stderr.

Clone this wiki locally