-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathxtrace.sh
executable file
·91 lines (66 loc) · 1.67 KB
/
xtrace.sh
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/bin/bash
################################################
# #
# This is for /bin/bash scripts #
# You can't use this with /bin/sh scripts. #
# #
################################################
trap 'exec 2> /dev/null
rm -f $pipe
kill $print_pid
kill -- -$target_pid' EXIT
pipe=/tmp/pipe_$$
mkfifo $pipe
##### Check usage
if [ ${#@} -eq 0 ]; then
echo
echo Usage: "$(basename $0)" bash_script arg1 arg2 ...
echo
exit 1
else
target_command=$1
shift
fi
##### Trace functions
__trap_debug__() {
set -o monitor
suspend -f
set +o monitor
}
__trace_ON__() {
echo --------- trace ON -----------
set -o xtrace -o functrace
trap __trap_debug__ DEBUG
}
__trace_OFF__() {
trap - DEBUG
set +o xtrace +o functrace
echo --------- trace OFF -----------
}
export -f __trace_ON__ __trace_OFF__ __trap_debug__
##### Prompt for xtrace
export PS4='+\[\e[0;32m\]:\[\e[0;49;95m\]${LINENO}\[\e[0;32m\]:${FUNCNAME[0]:+${FUNCNAME[0]}(): }\[\e[0m\]'
##### Read from pipe and print xtrace
while read -r line; do
case $line in
*__trace_OFF__* ) continue ;;
*__trap_debug__* ) continue ;;
esac
echo "$line" >&2
done < $pipe &
print_pid=$!
##### Excute target command
# disable suspend
set -o monitor
# enable tracing for shell functions
bash -c "$target_command"' "$0" "$@"' "$@" &> $pipe &
target_pid=$!
##### Trace !
while read line; do
if kill -0 $target_pid 2> /dev/null; then
fg %% > /dev/null
sleep 0; echo -e "\e[0;34mDONE\e[0m"
else
exit
fi
done