10

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?

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.

  • The key for me to understand here was, quoting the argument initially will only preserve the whitespace until it is passed into consoleWriteLine. The second time it is echo'd, the whitespace needs to be preserved again by additional quotes. I would have never guessed that you can put quotes around $*. – Der Hochstapler May 8 '15 at 21:47
  • 4
    Not only can you put quotes around $*, the variant $@ was specifically created to expand into separate words when quoted: "$@" can be several arguments, "$*" is always just one. echo is one of the few commands where it makes no difference. – alexis May 9 '15 at 0:22
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

  • 2
    this is working, but the accepted solution (adding quotes) is much neater. – caesarsol May 8 '15 at 12:45
  • Nod, I didn't notice it wasn't quoted. Whoops! :D – djsmiley2k TMW May 12 '15 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.