Question

I am trying to implement an abort function in a bash script, currently it looks like this:

function abort {
  LOGFILE=/var/log/bash_test
  DATE=$(date "+%Y %b %a %H:%M:%S")
  printf "\n------| ERROR: %s line %03d in %s |------\n" "$DATE" "$2" "${0}" >> "$LOGFILE"
  echo "$1" >> "$LOGFILE"
}

abort "Some kind of error..." $LINENO

This will produce this in /var/log/bash_test

------| ERROR: 2014 Jan Tue 12:50:12 line 007 in /home/user/test.sh |------
Some kind of error

My question is this: The method of giving the line number manually (eg. $2 < $LINENO) is ugly and repetitive. Is there a way to make this function detect the $LINENO from outside the function automatically? So that i can give the command

abort "Some kind of error..."

And still get the line number?

Was it helpful?

Solution

You should be able to use BASH_LINENO:

$ cat test.sh 
my_environment() {
    echo "Stack size: ${#BASH_LINENO[@]}"
    echo "Caller line: ${BASH_LINENO[$((${#BASH_LINENO[@]} - 2))]}"
}
my_environment
$ sh test.sh 
Stack size: 2
Caller line: 5

That is, the second to last entry will be the line number where the call to my_environment happened.

From the man bash section about BASH_LINENO:

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

OTHER TIPS

with awk, you can get the line number. Below command will search the key word "ERROR" first, and export the line number.

awk '/ERROR/{print NR}' logfile
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top