Linux: Trimming spaces from variables

Problem


You've got spaces in a variable. This could happen when you are returning variables from a SQL statement. There is tons of advice on methods online, very few of it works.

Solution

Create a small function in your script. (put it just after your variable declarations)

function trim
{
    echo "$1" | sed -n '1h;1!H;${;g;s/^[ \t]*//g;s/[ \t]*$//g;p;}'
}

When you have a variable that needs trimming, pass it through the function.

trimmed=$( trim "$RETVAL" )

Acknowledgment


http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-a-bash-variable

Comments