How to trim whitespace from a Bash variable?

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

    This is the simplest method I've seen. It only uses Bash, it's only a few lines, the regexp is simple, and it matches all forms of whitespace:

    if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
    then 
        test=${BASH_REMATCH[1]}
    fi
    

    Here is a sample script to test it with:

    test=$(echo -e "\n \t Spaces and tabs and newlines be gone! \t  \n ")
    
    echo "Let's see if this works:"
    echo
    echo "----------"
    echo -e "Testing:${test} :Tested"  # Ugh!
    echo "----------"
    echo
    echo "Ugh!  Let's fix that..."
    
    if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
    then 
        test=${BASH_REMATCH[1]}
    fi
    
    echo
    echo "----------"
    echo -e "Testing:${test}:Tested"  # "Testing:Spaces and tabs and newlines be gone!"
    echo "----------"
    echo
    echo "Ah, much better."
    

提交回复
热议问题