Bash Snippet: Trim Function

Occasionally I find myself wanting to removing leading and/or trailing occurrences of a character or string from a larger string in bash. A couple common uses are removing quotes, or stripping an unknown number of spaces leading into the data of interest. This can be done pretty easily with other methods such as awk or sed, but with the disadvantage of requiring external commands. This a pure bash implementation using only shell built-ins. It might be better to rewrite this with $BASH_REMATCH, but this is what I currently have.


trim () {
    # trim spaces by default
    if [ -z "$match" ]; then
        match=" "
    # trim leading
    while [ "${str:0:${#match}}" == "$match" ];
    # trim tailing
    while [ "${str:$((${#str}-${#match}))}" == "$match" ];
        str="${str:0:$((${#str} - ${#match}))}"
    echo "$str"

#Remove leading and trailing spaces
example="    Hello     "
echo "`trim  "$example" " "`"

#The second parameter is optional when removing spaces
example="    Hello     "
echo "`trim  "$example"`"

#Remove leading and trailing occurences of "word"
echo "`trim  "$example" "word"`"
This entry was posted in Bash. Bookmark the permalink.

One Response to Bash Snippet: Trim Function

  1. Chris says:

    This deserves a look

    Much cleaner solution for removing leading and trailing whitespace, but I wasn’t having luck with getting it to remove character strings without sometimes clobbering the meat of my variable. Probably worth sitting down to make sense out of.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.