私は単にsedを使用します:
function trim
{
    echo "$1" | sed -n '1h;1!H;${;g;s/^[ \t]*//g;s/[ \t]*$//g;p;}'
}
a)単一行文字列の使用例
string='    wordA wordB  wordC   wordD    '
trimmed=$( trim "$string" )
echo "GIVEN STRING: |$string|"
echo "TRIMMED STRING: |$trimmed|"
出力:
GIVEN STRING: |    wordA wordB  wordC   wordD    |
TRIMMED STRING: |wordA wordB  wordC   wordD|
b)複数行文字列の使用例
string='    wordA
   >wordB<
wordC    '
trimmed=$( trim "$string" )
echo -e "GIVEN STRING: |$string|\n"
echo "TRIMMED STRING: |$trimmed|"
出力:
GIVEN STRING: |    wordAA
   >wordB<
wordC    |
TRIMMED STRING: |wordAA
   >wordB<
wordC|
c)最後の注記:
 
関数を使用したくない場合は、単一行の文字列の場合、次のような「覚えやすい」コマンドを使用できます。
echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
例:
echo "   wordA wordB wordC   " | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
出力:
wordA wordB wordC
複数行の文字列で上記を使用しても機能しますが、GuruMがコメントで気づいたように、末尾/先頭の内部の複数のスペースもカットされることに注意してください
string='    wordAA
    >four spaces before<
 >one space before<    '
echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
出力:
wordAA
>four spaces before<
>one space before<
したがって、それらのスペースを維持することを気にする場合は、私の回答の最初にある関数を使用してください!
d)関数trim内で使用される複数行の文字列に対するsed構文「検索および置換」の説明:
sed -n '
# If the first line, copy the pattern to the hold buffer
1h
# If not the first line, then append the pattern to the hold buffer
1!H
# If the last line then ...
$ {
    # Copy from the hold to the pattern buffer
    g
    # Do the search and replace
    s/^[ \t]*//g
    s/[ \t]*$//g
    # print
    p
}'