bash hr function

Reading time: about 1 minute

I write a lot of bash scripts to automate different facets of developer workflows, and the user interface of a script is a place I try to pay attention to.

It’s easy to write scripts which do the right thing, but it’s harder to write scripts which will be sturdy and insulated from bitrot inflicted as the architecture changes around them.

Adequate feedback is also really helpful. How do I know the script did the right thing?

One of the functions I think adds a lot to the output of a script is this little gem which prints an <hr> in the console:

hr() {
  # Text written into the horizontal rule, left justified
  length=$(echo "$text" | wc -m)


  # set the color
  echo -e -n "\033[30;47m"

  # print the message
  echo -n "$text"

  # finish the line across the console
  cols=$(expr "$(tput cols)" - $length)
  printf " %${cols}s"

  # clear the background color and start a new line
  echo -e "\033[0m"

It looks like this in the console:

Date: 2018-Jul-19
Tags: bash script user-interface
Previous: Notes on FRS, GMRS, MURS radios
Next: Notes on installing HKCam on a raspberry-pi with systemd