How to trim whitespace from a Bash variable?

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

    From Bash Guide section on globbing

    To use an extglob in a parameter expansion

     #Turn on extended globbing  
    shopt -s extglob  
     #Trim leading and trailing whitespace from a variable  
    x=${x##+([[:space:]])}; x=${x%%+([[:space:]])}  
     #Turn off extended globbing  
    shopt -u extglob  
    

    Here's the same functionality wrapped in a function (NOTE: Need to quote input string passed to function):

    trim() {
        # Determine if 'extglob' is currently on.
        local extglobWasOff=1
        shopt extglob >/dev/null && extglobWasOff=0 
        (( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.
        # Trim leading and trailing whitespace
        local var=$1
        var=${var##+([[:space:]])}
        var=${var%%+([[:space:]])}
        (( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off.
        echo -n "$var"  # Output trimmed string.
    }
    

    Usage:

    string="   abc def ghi  ";
    #need to quote input-string to preserve internal white-space if any
    trimmed=$(trim "$string");  
    echo "$trimmed";
    

    If we alter the function to execute in a subshell, we don't have to worry about examining the current shell option for extglob, we can just set it without affecting the current shell. This simplifies the function tremendously. I also update the positional parameters "in place" so I don't even need a local variable

    trim() {
        shopt -s extglob
        set -- "${1##+([[:space:]])}"
        printf "%s" "${1%%+([[:space:]])}" 
    }
    

    so:

    $ s=$'\t\n \r\tfoo  '
    $ shopt -u extglob
    $ shopt extglob
    extglob         off
    $ printf ">%q<\n" "$s" "$(trim "$s")"
    >$'\t\n \r\tfoo  '<
    >foo<
    $ shopt extglob
    extglob         off
    

提交回复
热议问题