How to trim whitespace from a Bash variable?

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

    There are a lot of answers, but I still believe my just-written script is worth being mentioned because:

    • it was successfully tested in the shells bash/dash/busybox shell
    • it is extremely small
    • it doesn't depend on external commands and doesn't need to fork (->fast and low resource usage)
    • it works as expected:
      • it strips all spaces and tabs from beginning and end, but not more
      • important: it doesn't remove anything from the middle of the string (many other answers do), even newlines will remain
      • special: the "$*" joins multiple arguments using one space. if you want to trim & output only the first argument, use "$1" instead
      • if doesn't have any problems with matching file name patterns etc

    The script:

    trim() {
      local s2 s="$*"
      until s2="${s#[[:space:]]}"; [ "$s2" = "$s" ]; do s="$s2"; done
      until s2="${s%[[:space:]]}"; [ "$s2" = "$s" ]; do s="$s2"; done
      echo "$s"
    }
    

    Usage:

    mystring="   here     is
        something    "
    mystring=$(trim "$mystring")
    echo ">$mystring<"
    

    Output:

    >here     is
        something<
    

提交回复
热议问题