Stripping Spaces in Bash

Here's how to strip leading and/or trailing spaces from a string with Bash:

Simple Method Using echo:

~$ T="    x y   "
~$ T="$(echo -n $T)"
~$ echo "1${T}2"
1x y2
~$ 

Use xargs, whose default command is /bin/echo, if your string is from standard input.

Complicated Method:

~$ shopt -s extglob
~$ T="     X           "
~$ T="${T%%*( )}"
~$ echo "1${T}2"
1     X2
~$ T="${T##*( )}"
~$ echo "1${T}2"
1X2
~$ 
To remove all types of whitespace, replace the space with [[:space:]] to look like this:
$ T="${T%%*([[:space:]])}"

The construct: *(pattern-list) requires the exglob option to be enabled. The constructs: ${parameter##word} & ${parameter%%word} are expansions to remove a matching prefix/suffix respectively.

Updated: .