Tuesday, March 7, 2017

Making BASH throw an error with the function name.

Debugging bash strings is just strange. I've just come across ${FUNCNAME[0]}, which returns the function that was called. In the following code, the testwithlen4() function expects a string with the length of 4, and if you give it short or long string, it returns the error with the name.
#!/bin/sh
echoerr() { echo "$@" 1>&2; }  # echo output to STDERR

testwithlen4()
{
  isom_inputstring=$1
  isom_inputsize=${#isom_inputstring}  #get the length, it should be 4
  isom_inputmaxsize=4
  if [ "$isom_inputsize" -ne "$isom_inputmaxsize" ]; then
    echoerr "ERROR, ${FUNCNAME[0]} failed due to isom_inputsize != $isom_inputmaxsize ($isom_inputsize) " 
    exit -1
  fi
testwithlen4 "abc"
The error result will be:
ERROR, testwithlen4 failed due to isom_inputsize != 4 (3)
Now to make a whole slew of changes to my support code. :/

No comments:

Post a Comment