Why does my script omit leading whitespace in console output?

I have the following script:

#!/bin/bash
function consoleWriteLine() {
  echo $* >&2
}

consoleWriteLine "    indented by 4 spaces"

When I run it, I get the following output:

$ ./test.sh
indented by 4 spaces

Where did my 4 spaces go? And how do I get them back?


Solution 1:

Just quote the echo in your function:

function consoleWriteLine() {
  echo "$*" >&2
}

echo just notices multiple arguments separated by space and prints them separated by a single space. See:

$ echo a b c
a b c
$ echo a b             c
a b c
$ echo "a b             c"
a b             c

In the last example the string a b c is one single argument and echoed as it is.

Solution 2:

Had this problem myself,

As per This blog you need to change the IFS as by default it contains white space and so sees "xxx yyy zzzz" as 3 strings with white space between them.

IFS='\n'

prior to the command will fix it, and unset IFS to remove the change

unset IFS