summaryrefslogtreecommitdiff
path: root/examples/scripts.v2/shprof
blob: 73a1bb97494086618389051b3e4c892d4886a5c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#! /bin/bash
#
# shprof - a line profiler for shell scripts
#
# adapted from a similar program included in `The New KornShell' by
# Bolsky and Korn and posted to usenet by bsh20858@challenger.fhda.edu
#
# converted to bash v2 syntax by Chet Ramey
#
TMPFILE=${TMP:-/tmp}/shprof$$

trap 'rm -f $TMPFILE' EXIT

errexit()
{
	echo $0: "$@" >&2
	exit 1
}

# create script with profiling enabled
cat > $TMPFILE <<- \_EOF_
	declare -a _line
	_profend()
	{
		case "$1" in
		/*|./*)	file="$1" ;;
		*) file=$(type -path "$1") ;;
		esac

		echo "*** line profile for $file ***"
		i=1;
		while read -r && [ $i -le $NLINE ]; do
			count=${_line[$i]}
			if [ "$count" -gt 0 ]; then
				echo "[$count] $i: $REPLY"
			fi
			i=$((i + 1))
		done <$file
_EOF_
# make the profiling script remove itself after printing line stats
echo "rm -f $TMPFILE" >> $TMPFILE
cat >> $TMPFILE <<- \_EOF_
	}
	_command=$1
	shift
	i=1
	NLINE=$(wc -l < "$_command")
	while [ $i -le $NLINE ]; do
		_line[$i]=0
		i=$((i + 1))
	done
	unset i
	trap "_profend ${_command}" EXIT
	trap '_line[$LINENO]=$((${_line[$LINENO]} + 1))' DEBUG
	LINENO=0
_EOF_

case "$1" in
/*|./*)	file=$1 ;;
*)	file=$((type -path "$1")) ;;
esac

cat "${file-$1}" >> $TMPFILE || errexit "${1}: cannot open"
chmod +x $TMPFILE

exec -a "$file" $TMPFILE "$@"