How do I echo a string with multiple spaces in bash “untouched”?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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

Method 2

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 '%sn' "$MYCUSTOMTAB"

printf '%sn' "${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 '%bn' "${MYCUSTOMTAB}blah blah"

For reference read Why is printf better than echo?

Method 3

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

echo -e "$MYCUSTOMTAB"."blah blah"

Method 4

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

printf "%sblah blahn" "$MYCUSTOMTAB"

or

someString="blah blah"
printf "%s%sn" "$MYCUSTOMTAB" "$someString"


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x