Skip to content

Commit 16a95a5

Browse files
committed
! show-busy-java-threads: improve self rerun command line in output
1 parent 91ca691 commit 16a95a5

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

bin/show-busy-java-threads

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,13 @@
2121

2222
# NOTE: DO NOT declare var PROG as readonly, because its value is supplied by subshell.
2323
PROG="$(basename "$0")"
24-
readonly -a COMMAND_LINE=("$0" "$@")
24+
# choosing between $0 and BASH_SOURCE
25+
# https://stackoverflow.com/a/35006505/922688
26+
# How can I get the source directory of a Bash script from within the script itself?
27+
# https://stackoverflow.com/questions/59895
28+
# Will $0 always include the path to the script?
29+
# https://unix.stackexchange.com/questions/119929
30+
readonly -a COMMAND_LINE=("${BASH_SOURCE[0]}" "$@")
2531
# Get current user name via whoami command
2632
# See https://www.lifewire.com/current-linux-user-whoami-command-3867579
2733
# Because if run command by `sudo -u`, env var $USER is not rewritten/correct, just inherited from outside!
@@ -95,6 +101,23 @@ logAndCat() {
95101
cat
96102
}
97103

104+
# print calling(quoted) command line which is able to copy and paste to rerun safely
105+
#
106+
# How to get the complete calling command of a BASH script from inside the script (not just the arguments)
107+
# https://stackoverflow.com/questions/36625593
108+
printCallingCommandLine() {
109+
local arg isFirst=true
110+
for arg in "${COMMAND_LINE[@]}"; do
111+
if $isFirst; then
112+
isFirst=false
113+
else
114+
printf ' '
115+
fi
116+
printf '%q' "$arg"
117+
done
118+
echo
119+
}
120+
98121
usage() {
99122
local -r exit_code="${1:-0}"
100123
(($# > 0)) && shift
@@ -315,7 +338,7 @@ trap "cleanupWhenExit" EXIT
315338

316339
headInfo() {
317340
colorEcho "0;34;42" ================================================================================
318-
echo "$(date "+%Y-%m-%d %H:%M:%S.%N") [$((i + 1))/$update_count]: ${COMMAND_LINE[*]}"
341+
echo "$(date "+%Y-%m-%d %H:%M:%S.%N") [$((i + 1))/$update_count]: $(printCallingCommandLine)"
319342
colorEcho "0;34;42" ================================================================================
320343
echo
321344
}
@@ -460,7 +483,7 @@ printStackOfThreads() {
460483
# current user is not root user, so can not run with sudo; print error message and rerun suggestion
461484
redPrint "[$idx] Fail to jstack busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user})."
462485
redPrint "User of java process($user) is not current user($USER), need sudo to rerun:"
463-
yellowPrint " sudo ${COMMAND_LINE[*]}"
486+
yellowPrint " sudo $(printCallingCommandLine)"
464487
normalPrint
465488
continue
466489
fi || {

0 commit comments

Comments
 (0)