Skip to main content

Trim all whitespace from string and truncate spaces.

#
# Trim all whitespace from string and truncate spaces
# Source: https://github.com/dylanaraps/pure-bash-bible#trim-all-white-space-from-string-and-truncate-spaces
# shellcheck disable=SC2086,SC2048
collapse_spaces() {
    if [ -z "$1" ]; then
        echo "Usage: collapse_spaces <string>"
        echo "       Trim all whitespace from string and truncate spaces."
    else
        # Usage: collapse_spaces "   example   string    "
        set -f
        set -- $*
        printf '%s\n' "$*"
        set +f
    fi
}