31

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.
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
MatthewRock
  • 6,826
  • 6
  • 31
  • 54

2 Answers2

47

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
  • 150,973
  • 38
  • 327
  • 406
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"