16

This question already has an answer here:

I assigned a var like this:

MYCUSTOMTAB='     '

But using it in echo both:

echo $MYCUSTOMTAB"blah blah"

or

echo -e $MYCUSTOMTAB"blah blah"

just returns a single space and the rest of the string:

 blah blah

How can I print the full string untouched? I want to use it for have a custom indent because \t is too much wide for my tastes.

marked as duplicate by Gilles bash Apr 1 '16 at 15:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

24

Put your variable inside double quote to prevent field splitting, which ate your spaces:

$ MYCUSTOMTAB='     '
$ echo "${MYCUSTOMTAB}blah blah"
     blah blah
8

As suggested in this answer quoting the variable is enough.

The reason why quoting is needed in your case is because without it bash applies the split+glob operator onto the expansion of $MYCUSTOMTAB. The default value of $IFS contains the TAB character, so in echo -e $MYCUSTOMTAB"blah blah", $MYCUSTOMTAB is just split into nothing so it becomes the same as if you had written:

echo -e "blah blah"

(you probably don't want -e here btw).

You can also use printf instead of echo:

printf '%s\n' "$MYCUSTOMTAB"

printf '%s\n' "${MYCUSTOMTAB}blah blah"

Or if you want printf to do the same kind of \n, \t expansions that echo -e does, use %b instead of %s:

printf '%b\n' "${MYCUSTOMTAB}blah blah"

For reference read Why is printf better than echo?

  • 2
    While strictly true, the cause here is totally unrelated to the difference between printf and echo. While printf is certainly more portable and has some upsides, its major downside is that it is ugly and unreadable, and way more difficult to understand. – Wouter Verhelst Apr 1 '16 at 14:50
  • 2
    printf is "better" if you use it properly: you need to write printf "blah%sblah\n" "$MYCUSTOMTAB" -- if the variable contains any %s, %d, etc, you'll get the wrong output otherwise. – glenn jackman Apr 1 '16 at 14:51
2

I think you just have to use double quotes for your variable

echo -e "$MYCUSTOMTAB"."blah blah"
  • This doesn't work for me. In output I get the dot - it's not a concatenation operator in this case. However the following is working: echo "$MYCUSTOMTAB""blah blah" – Jaro Apr 9 at 10:04
1

I know your question is tagged bash but anyway, for maximum portability and reliability, I would use:

printf "%sblah blah\n" "$MYCUSTOMTAB" 

or

someString="blah blah"
printf "%s%s\n" "$MYCUSTOMTAB" "$someString"

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