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