How to trim whitespace from a Bash variable?

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

    # Trim whitespace from both ends of specified parameter
    
    trim () {
        read -rd '' $1 <<<"${!1}"
    }
    
    # Unit test for trim()
    
    test_trim () {
        local foo="$1"
        trim foo
        test "$foo" = "$2"
    }
    
    test_trim hey hey &&
    test_trim '  hey' hey &&
    test_trim 'ho  ' ho &&
    test_trim 'hey ho' 'hey ho' &&
    test_trim '  hey  ho  ' 'hey  ho' &&
    test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
    test_trim $'\n' '' &&
    test_trim '\n' '\n' &&
    echo passed
    

提交回复
热议问题