How to trim whitespace from a Bash variable?

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

    Strip one leading and one trailing space

    trim()
    {
        local trimmed="$1"
    
        # Strip leading space.
        trimmed="${trimmed## }"
        # Strip trailing space.
        trimmed="${trimmed%% }"
    
        echo "$trimmed"
    }
    

    For example:

    test1="$(trim " one leading")"
    test2="$(trim "one trailing ")"
    test3="$(trim " one leading and one trailing ")"
    echo "'$test1', '$test2', '$test3'"
    

    Output:

    'one leading', 'one trailing', 'one leading and one trailing'
    

    Strip all leading and trailing spaces

    trim()
    {
        local trimmed="$1"
    
        # Strip leading spaces.
        while [[ $trimmed == ' '* ]]; do
           trimmed="${trimmed## }"
        done
        # Strip trailing spaces.
        while [[ $trimmed == *' ' ]]; do
            trimmed="${trimmed%% }"
        done
    
        echo "$trimmed"
    }
    

    For example:

    test4="$(trim "  two leading")"
    test5="$(trim "two trailing  ")"
    test6="$(trim "  two leading and two trailing  ")"
    echo "'$test4', '$test5', '$test6'"
    

    Output:

    'two leading', 'two trailing', 'two leading and two trailing'
    

提交回复
热议问题