How to trim whitespace from a Bash variable?

后端 未结 30 2862
星月不相逢
星月不相逢 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
    2020-11-22 06:49

    There is a solution which only uses Bash built-ins called wildcards:

    var="    abc    "
    # remove leading whitespace characters
    var="${var#"${var%%[![:space:]]*}"}"
    # remove trailing whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   
    printf '%s' "===$var==="
    

    Here's the same wrapped in a function:

    trim() {
        local var="$*"
        # remove leading whitespace characters
        var="${var#"${var%%[![:space:]]*}"}"
        # remove trailing whitespace characters
        var="${var%"${var##*[![:space:]]}"}"   
        printf '%s' "$var"
    }
    

    You pass the string to be trimmed in quoted form. e.g.:

    trim "   abc   "
    

    A nice thing about this solution is that it will work with any POSIX-compliant shell.

    Reference

    • Remove leading & trailing whitespace from a Bash variable (original source)

提交回复
热议问题