My idea is to base on PGID (Process Group Identifier) and SID (Session identifier). Unless you source your script directly from a session leader, the following solution works. On the other hand, session leaders are mostly daemons and interactive shells. You can verify which processes run as session leaders by ps aux | awk '$8 ~ /s/ { print }'.
Source
/tmp/my_quit.sh:
get_pid()
{
pgid=$( ps -q $$ -o pgid= )
sid=$( ps -q $$ -o sid= )
if [[ $pgid == $sid ]]; then
echo 0
else
echo $pgid
fi
}
fatal()
{
echo "1"
}
die_if_fatal()
{
if [ $(fatal) -ne 0 ]; then
pid=$( get_pid )
if [ $pid -ne 0 ]; then
echo " >> Kill $pid"
kill $pid
else
return
fi
fi
echo "Rest of die_if_fatal's logic"
}
die_if_fatal
echo " >> Sourced from a session leader. Will not end the process."
/tmp/pack1.sh:
echo "$0: PID: $$ PGID: $( ps -q $$ -o pgid= ) SID=$( ps -q $$ -o sid= )"
echo " >> Sourcing my_quit..."
. /tmp/my_quit.sh
echo " >> Executing my_quit..."
/tmp/my_quit.sh
/tmp/pack2.sh:
echo "$0: PID: $$ PGID: $( ps -q $$ -o pgid= ) SID=$( ps -q $$ -o sid= )"
echo "Sourcing pack1..."
. /tmp/pack1.sh
echo "Executing pack1"
/tmp/pack1.sh
Use cases
Executing die_if_fatal (my_quit.sh) directly from shell - no script above
Execute the script:
[kan@pckan ~]$ /tmp/my_quit.sh
>> Kill 11360
Finished
[kan@pckan ~]$
Source the script:
[kan@pckan ~]$ . /tmp/my_quit.sh
>> Sourced from a session leader. Will not end the process.
[kan@pckan ~]$
Executing from pack1.sh - 1 level of nesting
Executing pack1.sh from shell:
[kan@pckan ~]$ /tmp/pack1.sh
/tmp/pack1.sh: PID: 11260 PGID: 11260 SID= 1630
>> Sourcing my_quit...
>> Kill 11260
Finished
[kan@pckan ~]$
Sourcing pack1.sh from shell:
[kan@pckan ~]$ . /tmp/pack1.sh
/bin/bash: PID: 1630 PGID: 1630 SID= 1630
>> Sourcing my_quit...
>> Sourced from a session leader. Will not end the process.
>> Executing my_quit...
>> Kill 11316
Finished
[kan@pckan ~]$
Executing from pack2.sh - 2 (and possibly more) levels of nesting
Executing pack2.sh from shell:
[kan@pckan ~]$ /tmp/pack2.sh
/tmp/pack2.sh: PID: 11535 PGID: 11535 SID= 1630
Sourcing pack1...
/tmp/pack2.sh: PID: 11535 PGID: 11535 SID= 1630
>> Sourcing my_quit...
>> Kill 11535
Finished
[kan@pckan ~]$
Sourcing pack2.sh from shell:
[kan@pckan ~]$ . /tmp/pack2.sh
/bin/bash: PID: 1630 PGID: 1630 SID= 1630
Sourcing pack1...
/bin/bash: PID: 1630 PGID: 1630 SID= 1630
>> Sourcing my_quit...
>> Sourced from a session leader. Will not end the process.
>> Executing my_quit...
>> Kill 11618
Finished
Executing pack1
/tmp/pack1.sh: PID: 11627 PGID: 11627 SID= 1630
>> Sourcing my_quit...
>> Kill 11627
Finished
[kan@pckan ~]$