-
Notifications
You must be signed in to change notification settings - Fork 0
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+
source "/path/to/options.bash/string.sh"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: helloReturn 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: 5Create 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).
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.
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.
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-
string::cleanandstring::lengthare ANSI-aware only when an ANSI module (ansi.shoransi-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.