How to trim whitespace from a Bash variable?

后端 未结 30 2677
星月不相逢
星月不相逢 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

    In order to remove all the spaces from the beginning and the end of a string (including end of line characters):

    echo $variable | xargs echo -n
    

    This will remove duplicate spaces also:

    echo "  this string has a lot       of spaces " | xargs echo -n
    

    Produces: 'this string has a lot of spaces'

提交回复
热议问题