How to trim whitespace from a Bash variable?

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

    Bash has a feature called parameter expansion, which, among other things, allows string replacement based on so-called patterns (patterns resemble regular expressions, but there are fundamental differences and limitations). [flussence's original line: Bash has regular expressions, but they're well-hidden:]

    The following demonstrates how to remove all white space (even from the interior) from a variable value.

    $ var='abc def'
    $ echo "$var"
    abc def
    # Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.
    $ echo -n "${var//[[:space:]]/}"
    abcdef
    

提交回复
热议问题