39

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.

user3450548
  • 2,868

4 Answers4

52

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

$ MYCUSTOMTAB='     '
$ echo "${MYCUSTOMTAB}blah blah"
     blah blah
cuonglm
  • 153,898
13

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?

techraf
  • 5,941
  • 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 01 '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 01 '16 at 14:51
2

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

echo -e "$MYCUSTOMTAB"."blah blah"
mnille
  • 529
  • 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 09 '19 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"
jlliagre
  • 61,204