32

I have a variable for color. I use it to set color to strings, by evaluating it inside the string. However, I need to include space after the name(so that the name doesn't contain part of the text). This sometimes looks bad.

How can I avoid using(printing) this space?

Example(Let's say that Red=1 and NC=2):

echo -e "$Red Note: blabla$NC".

Output:

1 Note: blabla2.

Expected output:

1Note: blabla2.
MatthewRock
  • 6,986

2 Answers2

49

Just enclose variable in braces:

echo -e "${Red}Note: blabla${NC}".

See more detail about Parameter Expansion.

See also great answer Why printf is better than echo? if you care about portability.

cuonglm
  • 153,898
7

What you should get into the habit of using is printf:

printf '%sNote: blabla%s\n' "$Red" "$NC"

Where each %s replace a variable. And the -e is not needed as printf accepts backslash values \n,\t, etc in a portable manner.

Remember that echo -e is not portable to other shells.

Other options:

You could use two commands that concatenate their output:

echo -ne "$Red"; echo -e "Note: blabla$NC"

You could use simple string concatenation:

echo -e "$Red""Note: blabla$NC"

Or you could make use of { } to avoid name-text confusions:

echo -e "${Red}Note: blabla$NC"