Remove Leading Whitespace from Bash Variable
If you have a variable with an unknown amount of leading whitespace, for example:
You can use this bash command to give you the value without any leading whitespaces
What is that?!
It's not nearly as complicated as it looks. The bash construct ${parameter##word}
removes the longest matching prefix of the pattern word
from the variable parameter
. The pattern we use is *( )
which is bash speak for zero or more occurrences of space.
EDIT: If this doesn't seem to do anything at all, you might need to enable extglob
. Do this by running the command shopt +s extglob
before doing the substitution.
A neat hack
You can achieve a similar result by taking advantage of the way bash expands command arguments. echo Hello
and echo Hello
are both treated as calling echo with one parameter, Hello
. That means to trim whitespace from a string, we can just echo it.
Be careful though. This will shorten all whitespace, so Hello World
will become Hello World