Bash

Trim Whitespace from String

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Strip leading and trailing whitespace without spawning sed or awk. Uses extglob + parameter expansion — much faster in tight loops than a subshell.
Bash
Raw
trim() {
    local s="$*"
    # Strip leading whitespace
    s="${s#"${s%%[![:space:]]*}"}"
    # Strip trailing whitespace
    s="${s%"${s##*[![:space:]]}"}"
    printf '%s' "$s"
}

trim "   hello world   "          # "hello world"
trim $'\t\n  spaces  \n\t'         # "spaces"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.