...soul, as in software?

Rantings about life.


Sat, 17 Aug 2013

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:

[1]: export FOO=${FOO}${FOO+,}myfoo

There are two obvious cases:

a) FOO wasn't previously set, hence FOO=myfoo after [1] is executed

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

posted at: 18:17 | path: | permanent link to this entry

Valid XHTML 1.1 Valid CSS! powered by blosxom Debian GNU/Linux VPS hosting by RimuHosting