How to trim whitespace from a Bash variable?

后端 未结 30 2817
星月不相逢
星月不相逢 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:43

    This worked for me:

    text="   trim my edges    "
    
    trimmed=$text
    trimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front
    trimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back
    
    echo "<$trimmed>" #Adding angle braces just to make it easier to confirm that all spaces are removed
    
    #Result
    
    

    To put that on fewer lines for the same result:

    text="    trim my edges    "
    trimmed=${${text##+( )}%%+( )}
    

提交回复
热议问题