The Computer Oracle

Why does my script omit leading whitespace in console output?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Why Does My Script Omit Leading Whitespace In Console Output?
00:17 Answer 1 Score 4
00:41 Accepted Answer Score 22
01:07 Thank you

--

Full question
https://superuser.com/questions/912290/w...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#bash

#avk47



ACCEPTED ANSWER

Score 22


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.




ANSWER 2

Score 4


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