How to trim whitespace from a Bash variable?

后端 未结 30 2680
星月不相逢
星月不相逢 2020-11-22 06:09

I have a shell script with this code:

var=`hg st -R \"$path\"`
if [ -n \"$var\" ]; then
    echo $var
fi

But the conditional code always ex

30条回答
  •  别那么骄傲
    2020-11-22 06:38

    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.

提交回复
热议问题