|
21 | 21 |
|
22 | 22 | # NOTE: DO NOT declare var PROG as readonly, because its value is supplied by subshell. |
23 | 23 | 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]}" "$@") |
25 | 31 | # Get current user name via whoami command |
26 | 32 | # See https://www.lifewire.com/current-linux-user-whoami-command-3867579 |
27 | 33 | # Because if run command by `sudo -u`, env var $USER is not rewritten/correct, just inherited from outside! |
@@ -95,6 +101,23 @@ logAndCat() { |
95 | 101 | cat |
96 | 102 | } |
97 | 103 |
|
| 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 | + |
98 | 121 | usage() { |
99 | 122 | local -r exit_code="${1:-0}" |
100 | 123 | (($# > 0)) && shift |
@@ -315,7 +338,7 @@ trap "cleanupWhenExit" EXIT |
315 | 338 |
|
316 | 339 | headInfo() { |
317 | 340 | 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)" |
319 | 342 | colorEcho "0;34;42" ================================================================================ |
320 | 343 | echo |
321 | 344 | } |
@@ -460,7 +483,7 @@ printStackOfThreads() { |
460 | 483 | # current user is not root user, so can not run with sudo; print error message and rerun suggestion |
461 | 484 | redPrint "[$idx] Fail to jstack busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user})." |
462 | 485 | redPrint "User of java process($user) is not current user($USER), need sudo to rerun:" |
463 | | - yellowPrint " sudo ${COMMAND_LINE[*]}" |
| 486 | + yellowPrint " sudo $(printCallingCommandLine)" |
464 | 487 | normalPrint |
465 | 488 | continue |
466 | 489 | fi || { |
|
0 commit comments