/ iffmain
iffmain
 1  #!/usr/bin/env perl
 2  
 3  =head1 SYNOPSIS
 4  print bash code to test if script is run or sourced
 5  output code tests if we are run directly from a script (vs source/testing)
 6  if from script:
 7   - execute provided main function
 8   - in bash "strict" mode 
 9   - with an exit trap
10  
11  =head1 USAGE
12  
13  in a bash/library with "mainfunc" defined use near end of file/script
14  
15     eval "$(iffmain "mainfunc")"
16  
17  =cut
18  
19  # read from end of this file
20  # replace MAINFUNCNAME in template below with first input argument
21  my $main_and_args=join(" ", @ARGV);
22  while(<DATA>){
23    s/MAINFUNCNAME/$main_and_args/g;
24    print
25  }
26  
27  # also see  $(caller); $BASH_COMMAND:$LINENO ($BASH_LINENO)
28  __DATA__
29  if [[ "$(caller)" == "0 "* ]]; then
30    set -euo pipefail
31    trap 'e=$?; [ $e -ne 0 ] && echo "$0 exited in error $e"' EXIT
32    MAINFUNCNAME "$@"
33    exit $?
34  fi