How to trim whitespace from a Bash variable?

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

    I've seen scripts just use variable assignment to do the job:

    $ xyz=`echo -e 'foo \n bar'`
    $ echo $xyz
    foo bar
    

    Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).

    I would also recommend always double-quoting variable substitutions in shell conditionals:

    if [ -n "$var" ]; then
    

    since something like a -o or other content in the variable could amend your test arguments.

提交回复
热议问题