How to trim whitespace from a Bash variable?

A simple answer is:

echo "   lol  " | xargs

Xargs will do the trimming for you. It’s one command/program, no parameters, returns the trimmed string, easy as that!

Note: this doesn’t remove all internal spaces so "foo bar" stays the same; it does NOT become "foobar". However, multiple spaces will be condensed to single spaces, so "foo bar" will become "foo bar". In addition it doesn’t remove end of lines characters.

Leave a Comment