Variables can only be set with strings of text or numbers not other macros or classes of css, so when you set <<set $red = "redbg">> you are setting the variable to the letters of r.e.d.b.g. as a text string, not as a reference to your .redbg class. Here is another way:
.redbg {background: red;}
.bluebg {background: blue;}
<div class="redbg">This div was set as a red background</div>
<<timed 2s>><<addclass ".redbg" "bluebg">><</timed>>
Using the <<addclass> macro will change any class you specify. You can set the <<addclass>> macro in a <<replace>>, <<link>> or <<timed>> macro to make the change in the passage.
more info:
http://www.motoslave.net/sugarcube/2/docs/macros.html#macros-addclass