Funny Shell trick

While sorting out a debian .bashrc file, I came across to this construct:


I found interesting the ${HISTCONTROL+,} construct, which will evaluate to a comma (,) if HISTCONTROL is defined, to the empty string otherwise (I checked).

It is useful to enrich (i.e., add while preserving the previous values) variables with new values that must be comma-separated.

I’ll try to explain this further.

Let’s assume that we have an enviroment variable FOO that controls the behaviour of some program. We want to make sure that the FOO var holds the value bar, but we don’t know if some other scriptlet in the chain has already set some other value(s) to this var. So, in order to preserve possibe preset values for FOO, we do this:

$ export FOO=${FOO}${FOO+,}myfoo  

There are two obvious cases:

a) FOO wasn’t previously set, hence FOO=myfoo after ¹ is executed

b) FOO was previously set with, say FOO=bar,baz. Then, after ¹ is executed, FOO will be FOO=bar,baz,myfoo. Note the comma between baz and myfoo. That’s the doing of ${FOO+,}.

pancho horrillo
I do things with computers.