1

I have a simple bash script that looks like this:

RED=$(tput setaf 1)
echo "$REDERROR - ..."

and I want it to print ERROR in red.

If i change my code to this:

RED=$(tput setaf 1)
echo "$RED ERROR - ..."

it prints ERROR in red but with a leading space.

So how can I eliminate that leading space and still reference my variable $RED before it?

Catfish
  • 18,876
  • 54
  • 209
  • 353

2 Answers2

5

Use curly braces:

echo "${RED}ERROR - ..."

String concatenation also works:

echo "$RED""ERROR - ..."

(Quotes around $RED aren't technically needed given its particular contents (no spaces or other field seperators) and therefore echo $RED"ERROR - ..." will give the same result.)

Community
  • 1
  • 1
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 1
    @Catfish For newbies I highly recommend against the second command. You should quote everything before you've learned your way around and are sure about what you're doing. Also, the first command is more elegant with color coding. – 4ae1e1 Apr 10 '15 at 16:39
  • @4ae1e1 Agreed, I also used to quote defensively in bash before I learned where in particular I really don't need to quote. As a matter of fact, the second command started as `"$RED""ERROR - ..."` as you can see in the revisions. – Petr Skocik Apr 10 '15 at 16:50
  • That's actually better! – 4ae1e1 Apr 10 '15 at 16:51
  • The suggestion to use curly braces is awesome, simple, canonical and correct in all cases always: +1. I took the liberty of just skipping the concatenation suggestion since it only [muddles and dilutes](http://www.bloomberg.com/bw/articles/2012-11-29/beware-the-presenters-paradox) the awesomeness ^^ – that other guy Apr 10 '15 at 16:58
1

You can use:

 echo $RED"ERROR - ..."
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57