How to trim whitespace from a Bash variable?

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

    Python has a function strip() that works identically to PHP's trim(), so we can just do a little inline Python to make an easily understandable utility for this:

    alias trim='python -c "import sys; sys.stdout.write(sys.stdin.read().strip())"'
    

    This will trim leading and trailing whitespace (including newlines).

    $ x=`echo -e "\n\t   \n" | trim`
    $ if [ -z "$x" ]; then echo hi; fi
    hi
    

提交回复
热议问题