jazz/11-03-31: shprof

File shprof, 1.3 KB (added by jazz, 13 years ago)
Line 
1#! /bin/bash
2#
3# shprof - a line profiler for shell scripts
4#
5# http://www.math.ias.edu/doc/bash-3.0/scripts.v2/shprof
6#
7# adapted from a similar program included in `The New KornShell' by
8# Bolsky and Korn and posted to usenet by bsh20858@challenger.fhda.edu
9#
10# converted to bash v2 syntax by Chet Ramey
11#
12TMPFILE=${TMP:-/tmp}/shprof$$
13
14trap 'rm -f $TMPFILE' EXIT
15
16errexit()
17{
18  echo $0: "$@" >&2
19  exit 1
20}
21
22# create script with profiling enabled
23cat > $TMPFILE <<- \_EOF_
24  declare -a _line
25  _profend()
26  {
27    case "$1" in
28    /*|./*) file="$1" ;;
29    *) file=$(type -path "$1") ;;
30    esac
31
32    echo "*** line profile for $file ***"
33    i=1;
34    while read -r && [ $i -le $NLINE ]; do
35      count=${_line[$i]}
36      if [ "$count" -gt 0 ]; then
37        echo "[$count] $i: $REPLY"
38      fi
39      i=$((i + 1))
40    done <$file
41_EOF_
42# make the profiling script remove itself after printing line stats
43echo "rm -f $TMPFILE" >> $TMPFILE
44cat >> $TMPFILE <<- \_EOF_
45  }
46  _command=$1
47  shift
48  i=1
49  NLINE=$(wc -l < "$_command")
50  while [ $i -le $NLINE ]; do
51    _line[$i]=0
52    i=$((i + 1))
53  done
54  unset i
55  trap "_profend ${_command}" EXIT
56  trap '_line[$LINENO]=$((${_line[$LINENO]} + 1))' DEBUG
57  LINENO=0
58_EOF_
59
60case "$1" in
61/*|./*) file=$1 ;;
62*)  file=$((type -path "$1")) ;;
63esac
64
65cat "${file-$1}" >> $TMPFILE || errexit "${1}: cannot open"
66chmod +x $TMPFILE
67
68exec -a "$file" $TMPFILE "$@"