Trap --- print stack trace when error occure

Given a main script that call scripts which themselves execute other scripts.

/a/main.sh
/a/b/c/script1.sh

/a/b/c/script1.sh
/a/b/script2.sh

/a/b/script2.sh
/a/d/e/script3.sh

An error occurs in script3.sh

Question 1 :

How to have the trap function in the main script showing a stack trace like :
/a/main.sh
/a/b/c/script1.sh
/a/b/script2.sh
/a/d/e/script3.sh : line : xyz — error code : 123

Question 2 :

I use a script ‘/a/my_function.sh’ that contains a lot a bash functions
This script is sourced in /a/main.sh
source /a/my_function.sh

Now a ‘script4.sh’ call a function in ‘/a/my_function.sh’
An error occurs in ‘/a/d/script4.sh’

How to have the trap function in the main script showing a stack trace like
/a/main.sh
/a/d/script4.sh
/a/my_function.sh : line : xyz — function : get_leap_version — error code : 456

Currently all scripts unless the function script ‘/a/my_function.sh’ contains :

	shopt -s inherit_errexit # Enable (set) each optname.
	set -E # ~ trap on ERR is inherited
	set -T # ~ trap on DEBUG and RETURN are inherited
	set -o errexit # ~ set -e
	set -o nounset # ~ set -u
	set -o pipefail
	set -o functrace

How script3.sh is supposed to know that it has been invoked by script2.sh? If you really insist on this, you need to parse process list following parent process numbers starting with $PPID.

OK.
Now script3.sh call a function in a script sourced by main.sh at startup.
When an error occurs in the function I got the line number in script3.sh where the function is called, but not the line number where the function failed.
The trap knows nothing about the failed function.
Is it possible to solve this ignorance.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.