0

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?
Community
  • 1
  • 1
Lone Learner
  • 18,088
  • 20
  • 102
  • 200

3 Answers3

0

If the variable a is set with something like "-e", "-n" in the begining, depending on how you process later your result, a user might crash your script: -e option allows echo to interpret things backslashed.

Even in the case you only want to display the variable a, -n would screw your layout.

You could think about using regex to check if your variable starts with '-' and is followed by one of the available echo options (-n, -e, -E, --help, --version).

Vladimir T.
  • 199
  • 4
  • This is a good point, so I am using the `printf` command now instead of `echo` command which is robust to strings like `-e` or `-n`. Therefore, I still have the two questions I asked in this post. – Lone Learner Mar 26 '15 at 09:46
0

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
Lone Learner
  • 18,088
  • 20
  • 102
  • 200
0

You could use Bash's builtin pattern substitution. Note: Bash pattern substitution uses 'Pathname Expansion' (glob) pattern matching, not regular expressions. My solution requires enabling the optional shell behaviour extglob (shopt -s extglob).

$shopt -s extglob
$ a="  foo bar  "
$ echo "Remove trailing spaces: '${a/%*([[:space:]])}'"
Remove trailing spaces: '  foo bar'
$ echo "Remove leading spaces: '${a/#*([[:space:]])}'"
Remove leading spaces: 'foo bar  '
$ echo "Remove all spaces anywhere: '${a//[[:space:]]}'"
Remove all spaces anywhere: 'foobar'

For reference, refer to the 'Parameter Expansion' (Pattern substitution) and 'Pathname Expansion' subsections of the EXPANSION section of the Bash man page.

Iain
  • 1