Search code examples
shellposix

How to trim leading and trailing whitespaces from a string value in a variable?


I know there is a duplicate for this question already at: How to trim whitespace from a Bash variable?.

I read all the answers there but I have a question about another solution in my mind and I want to know if this works.

This is the solution I think works.

a=$(printf "%s" $a)

Here is a demonstration.

$ a="  foo  "
$ a=$(printf "%s" $a)
$ echo "$a"
foo
  1. Is there any scenario in which this solution may fail?
  2. If there is such a scenario in which this solution may fail, can we modify this solution to handle that scenario without compromising the simplicity of the solution too much?

Solution

  • It fails when the input contains spaces between non-whitespace characters.

    $ a="  foo  bar  "
    $ a=$(printf "%s" $a)
    $ echo "$a"
    foobar
    

    The expected output was the following instead.

    foo  bar