Functional Scripting tricks

As I code and work more and more in this field of Information Technology that is now begin called DevOps, I begin to develop certain tricks that I form into a style.

Here are a few to play with:

- () { return; }

Now you can use the ‘-‘ at the beginning of a line as way
to leave comments. You should probably use this for structured comments that you might want to grab via reflection.

color() {
# The next line is functionally a comment too.
- alp color white red green blue
# If you overload the '-' function, then
# the color comment will become a function call
 if [ -n $1 ]; then
     case $1 in
       white)  FG='00m' ;;
       red)    FG='31m' ;;
       green)  FG='32m' ;; 
       blue)   FG='34m' ;;
      esac;
      printf "\033[$FG";
  fi
}

You can experiment around with what symbols you can overload in this way. So far, I found:

, . - + @

In what my structured comment line, I begin with the word ‘alp’. I will now define what ‘alp’ does.

# alp creates a function for each option defined
alp ()
{
- alp $1 $2
T=/tmp/$$
echo "$1.$2() { $1 $2; }" > $T
source $T
rm $T
}
alp color red
alp color blue
alp color white
alp color green

Now you have four new functions, one for each color.

declare -f color.red
color.red ()
{
    color red
}

So this is how I play with bash. It is very similar to how one might approach golang, python, or other functional languages.