Ring Buffers with Bash Script

This post is a little bit infantile, since it does present a really, really simple thing, but I wrote the shell code yesterday for a backup script and it seems as I will not need it. So I write it down here so either I do not forget it (who knows when it will come in handy?) or perhaps someone else says: “Hey my script could be much easier using this”. In the next days I will post the code that replaces the code shown in this post, so stay tuned.

Here is a short bash function, that offers you to retrieve the value of the index in a ring buffer for a given position argument:

function ring () {
  if (( ($1 % $2) < 0 )); then
    ringval=$(($2 + ($1 % $2)))
  else
    ringval=$(($1 % $2))
  fi
  if (( "$ringval" < 10  )); then
    echo "0$ringval"
  else
    echo "$ringval"
  fi
}

function stripzeros () {
  stripped=${1#"${1%%[!0]*}"}
  if [ -z "$stripped" ]; then
    echo "0"
  else
    echo $stripped
  fi
}

# e.g.: 08
currhour="`date \"+%H\"`"

# e.g.; 07
lasthour=$(ring $(($(stripzeros ${currhour})-1)) "24")

The padding and stripping of zeros could be scripted much more elegantly and reliable, but for representing hours of a day this suffices. If someone creates a general script out of it, please feel free to send it in a comment to me, I will add it to this post.

Leave a Reply

Your email address will not be published. Required fields are marked *