shell programming - 2nd order reference

created onJanuary 18, 2022

A 2nd order reference is a reference that references the variable with the name which is the value in the referencing variable. I.e.:

$ fruit="banana" $ food="fruit" $ printf "%s\n" ${!food} banana

The value of the 2nd variable (food) is the name of the 1st variable (fruit). Dereferencing the value of the 1 variable is done by preceding the second variable with an exlamation mark .

You can also dereference a 2nd order variable with :

$ eval someFood=\$${food} $ printf "%s\n" ${someFood} banana

So, one might ask, what’s that good for?

a sample application of a 2nd order variable

Given a numer of variables that hold commands to set the terminal foreground colors and a command to reset the terminal foreground color back to normal:

lightblue = $( tput setaf 75 ) cyan = $( tput setaf 51 ) green = $( tput setaf 11 ) yellow = $( tput setaf 11 ) brightred = $( tput setaf 196 ) NORMAL = $( tput op )

and a function ‘logformat’ that dereferences the command to set the terminal color from the first function parameter, so that ‘logformat’ can be used like

logformat lightblue "some log msg"

The function ‘logformat’, which takes the color of the log label as an parameter, can be written as

logformat () { markercolor=$1 eval mcl=\$$markercolor shift echo "[${mcl}info${NORMAL}] $@" }

or with an additional parameter for the label and some some code to clear the current line:

# general log formatting logformat () { markercolor=$1 shift marker="$1" shift # reset cursor to beginning of line, clear to eol tput hpa 0 tput el echo "[${!markercolor}${marker}${NORMAL}] $@" }

Now we can write log functions that print out the log message with a colored label:

# log levels with log level marker and level specific marker color log_info () { logformat lightblue info $@ } log_warn() { logformat orange warn $@ } log_ok() { logformat green " ok " $@ } log_fail() { logformat brightred fail $@ } log_action() { logformat NORMAL "...." $@ }

Now we can log with some nice colors:

Note that the color definitions above do not work during the boot sequence. Linux prints out the boot msgs on a terminal with the 16 ANSI standard colors, which are different from the colors defined above.

source code download

shell code for log functions with colored loglevel markers   log.lib