Skip to content

Commit

Permalink
refactor: small code cleanup
Browse files Browse the repository at this point in the history
- merge `colorPrint` function if only one caller
- remove `local nl=$'\n'` declaration if only one usage
- remove unnecessary `{}` when use var
- use upper-case var name for global readonly vars
- use `=` instead of `==` in `Conditional Expressions`
- improve/fix/add code comments
- remove section comments for simple section
  • Loading branch information
oldratlee committed Feb 18, 2024
1 parent ebb62cd commit 4ad6b5b
Show file tree
Hide file tree
Showing 19 changed files with 89 additions and 114 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<a href="https://github.com/oldratlee/useful-scripts"><img src="https://img.shields.io/github/repo-size/oldratlee/useful-scripts" alt="GitHub repo size"></a>
</p>

🐌 useful scripts for making developer's everyday life easier and happier, involved java, shell etc.
🐌 useful scripts for making developer's everyday life easier and happier, involved java, shell etc.

👉 平时有用的手动操作做成脚本,以便捷地使用,让开发的日常生活更轻松些。 💕

Expand Down Expand Up @@ -143,7 +143,7 @@ PS:

- 目前仍然是主流的`Shell`,并且在不同环境基本上都缺省部署了。
-[`Google``Shell`风格指南](https://zh-google-styleguide.readthedocs.io/en/latest/google-shell-styleguide/background/)中,明确说到了:`Bash`**唯一**被允许执行的`shell`脚本语言。
- 统一用`Bash`可以避免差异带来的风险与没有收益的复杂性
- 统一用`Bash`可以避免不同`Shell`之间差异所带来的风险与没有收益的复杂性
- 有大量的`Shell`实现,`sh``bash``zsh``fish``csh``tcsh``ksh``ash``dash`……
- 不同的`Shell`有各种差异,深坑勿入。
- 个人系统学习过的是`Bash`,比较理解熟悉。
Expand All @@ -154,14 +154,14 @@ PS: 虽然交互`Shell`个人已经使用`Zsh` + [`oh-my-zsh`](https://ohmyz.sh/

> 更多资料参见 [子文档](docs/developer-guide.md)
- 开发规范与工具
- [**_`Google Shell Style Guide`_**](https://google.github.io/styleguide/shell.xml) | [中文版](https://zh-google-styleguide.readthedocs.io/en/latest/google-shell-styleguide/background/)
- 🛠️ 开发规范与工具
- [`Google Shell Style Guide`](https://google.github.io/styleguide/shell.xml) | [中文版](https://zh-google-styleguide.readthedocs.io/en/latest/google-shell-styleguide/background/)
- [`koalaman/shellcheck`](https://github.com/koalaman/shellcheck): `ShellCheck`, a static analysis tool for shell scripts
- [`mvdan/sh(shfmt)`](https://github.com/mvdan/sh): `shfmt` formats shell programs
- 👷 **`Bash/Shell`最佳实践与安全编程**文章
- [Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
- Bash Pitfalls: 编程易犯的错误 - 团子的小窝:[Part 1](http://kodango.com/bash-pitfalls-part-1) | [Part 2](http://kodango.com/bash-pitfalls-part-2) | [Part 3](http://kodango.com/bash-pitfalls-part-3) | [Part 4](http://kodango.com/bash-pitfalls-part-4) | [英文原文:Bash Pitfalls](http://mywiki.wooledge.org/BashPitfalls)
- [不要自己去指定sh的方式去执行脚本](https://github.com/oldratlee/useful-scripts/issues/57#issuecomment-326485965)
- [不要自己去指定`sh`的方式去执行脚本](https://github.com/oldratlee/useful-scripts/issues/57#issuecomment-326485965)
- 🎶 **Tips**
- [让你提升命令行效率的 Bash 快捷键 【完整版】](https://linuxtoy.org/archives/bash-shortcuts.html)
补充:`ctrl + x, ctrl + e` 就地打开文本编辑器来编辑当前命令行,对于复杂命令行特别有用
Expand Down
9 changes: 2 additions & 7 deletions bin/a2l
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ readonly PROG=${0##*/}
readonly PROG_VERSION='2.x-dev'

################################################################################
# util functions
# parse options
################################################################################

usage() {
Expand All @@ -39,10 +39,6 @@ progVersion() {
exit
}

################################################################################
# parse options
################################################################################

args=()
while (($# > 0)); do
case "$1" in
Expand All @@ -63,13 +59,12 @@ while (($# > 0)); do
break
;;
*)
# if not option, treat all follow arguments as args
# if not option, treat it and all follow arguments as args
args=(${args[@]:+"${args[@]}"} "$@")
break
;;
esac
done

readonly args

################################################################################
Expand Down
13 changes: 3 additions & 10 deletions bin/ap
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,17 @@ readonly PROG_VERSION='2.x-dev'
# util functions
################################################################################

colorPrint() {
local color=$1
shift
redPrint() {
# if stdout is a terminal, turn on color output.
# '-t' check: is a terminal?
# check isatty in bash https://stackoverflow.com/questions/10022323
if [ -t 1 ]; then
printf '\e[1;%sm%s\e[0m\n' "$color" "$*"
printf '\e[1;31m%s\e[0m\n' "$*"
else
printf '%s\n' "$*"
fi
}

redPrint() {
colorPrint 31 "$*"
}

die() {
redPrint "Error: $*" >&2
exit 1
Expand Down Expand Up @@ -75,8 +69,7 @@ usage() {
local -r out=$(((exit_code != 0) + 1))

# NOTE: $'foo' is the escape sequence syntax of bash
local nl=$'\n' # new line
(($# > 0)) && redPrint "$*$nl" >&"$out"
(($# > 0)) && redPrint "$*"$'\n' >&"$out"

cat >&"$out" <<EOF
Usage: $PROG [OPTION]... [FILE]...
Expand Down
1 change: 1 addition & 0 deletions bin/coat
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ rotateColorPrint() {
}

rotateColorPrintln() {
# NOTE: $'foo' is the escape sequence syntax of bash
rotateColorPrint "$*"$'\n'
}

Expand Down
3 changes: 1 addition & 2 deletions bin/cp-into-docker-run
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ usage() {
local -r out=$(((exit_code != 0) + 1))

# NOTE: $'foo' is the escape sequence syntax of bash
local nl=$'\n' # new line
(($# > 0)) && redPrint "$*$nl" >&"$out"
(($# > 0)) && redPrint "$*"$'\n' >&"$out"

cat >&"$out" <<EOF
Usage: $PROG [OPTION]... command [command-args]...
Expand Down
3 changes: 1 addition & 2 deletions bin/find-in-jars
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ usage() {
local -r out=$(((exit_code != 0) + 1))

# NOTE: $'foo' is the escape sequence syntax of bash
local -r nl=$'\n' # new line
(($# > 0)) && redPrint "$*$nl" >&"$out"
(($# > 0)) && redPrint "$*"$'\n' >&"$out"

cat >&"$out" <<EOF
Usage: $PROG [OPTION]... PATTERN
Expand Down
21 changes: 7 additions & 14 deletions bin/rp
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,17 @@ readonly PROG_VERSION='2.x-dev'
# util functions
################################################################################

colorPrint() {
local color=$1
shift
redPrint() {
# if stdout is a terminal, turn on color output.
# '-t' check: is a terminal?
# check isatty in bash https://stackoverflow.com/questions/10022323
if [ -t 1 ]; then
printf '\e[1;%sm%s\e[0m\n' "$color" "$*"
printf '\e[1;31m%s\e[0m\n' "$*"
else
printf '%s\n' "$*"
fi
}

redPrint() {
colorPrint 31 "$@"
}

die() {
redPrint "Error: $*" >&2
exit 1
Expand Down Expand Up @@ -73,17 +67,16 @@ usage() {
local -r out=$(((exit_code != 0) + 1))

# NOTE: $'foo' is the escape sequence syntax of bash
local nl=$'\n' # new line
(($# > 0)) && redPrint "$*$nl" >&"$out"
(($# > 0)) && redPrint "$*"$'\n' >&"$out"

cat >&"$out" <<EOF
Usage: ${PROG} [OPTION]... [FILE]...
Usage: $PROG [OPTION]... [FILE]...
convert to Relative Path.
Example:
${PROG} path # relative to current dir
${PROG} path1 relativeToPath
${PROG} */*.c relativeToPath
$PROG path # relative to current dir
$PROG path1 relativeToPath
$PROG */*.c relativeToPath
Options:
-h, --help display this help and exit
Expand Down
20 changes: 10 additions & 10 deletions bin/show-busy-java-threads
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,14 @@ usage() {
(($# > 0)) && colorPrint 31 "$*$NL" >&"$out"

cat >&"$out" <<EOF
Usage: ${PROG} [OPTION]... [delay [count]]
Usage: $PROG [OPTION]... [delay [count]]
Find out the highest cpu consumed threads of java processes,
and print the stack of these threads.
Example:
${PROG} # show busy java threads info
${PROG} 1 # update every 1 second, (stop by eg: CTRL+C)
${PROG} 3 10 # update every 3 seconds, update 10 times
$PROG # show busy java threads info
$PROG 1 # update every 1 second, (stop by eg: CTRL+C)
$PROG 3 10 # update every 3 seconds, update 10 times
Output control:
-p, --pid <java pid(s)> find out the highest cpu consumed threads from
Expand Down Expand Up @@ -215,7 +215,7 @@ ARGS=$(
usage 1
}
readonly ARGS
eval set -- "${ARGS}"
eval set -- "$ARGS"

count=5
cpu_sample_interval=0.5
Expand Down Expand Up @@ -525,20 +525,20 @@ printStackOfThreads() {
[ -f "$jstackFile" ] || {
# shellcheck disable=SC2206
local -a jstack_cmd_line=("$jstack_path" $force $mix_native_frames $lock_info $pid)
if [ "$user" == "$USER" ]; then
if [ "$user" = "$USER" ]; then
# run without sudo, when java process user is current user
logAndRun "${jstack_cmd_line[@]}" >"$jstackFile"
elif [ $UID == 0 ]; then
elif ((UID == 0)); then
# if java process user is not current user, must run jstack with sudo
logAndRun sudo -u "$user" "${jstack_cmd_line[@]}" >"$jstackFile"
else
# current user is not root user, so can not run with sudo; print error message and rerun suggestion
redOutput "[$idx] Fail to jstack busy(${pcpu}%) thread($threadId/$threadId0x) stack of java process($pid) under user($user)."
redOutput "[$idx] Fail to jstack busy($pcpu%) thread($threadId/$threadId0x) stack of java process($pid) under user($user)."
redOutput "User of java process($user) is not current user($USER), need sudo to rerun:"
yellowOutput " sudo $(printCallingCommandLine)"
continue
fi || {
redOutput "[$idx] Fail to jstack busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user})."
redOutput "[$idx] Fail to jstack busy($pcpu%) thread($threadId/$threadId0x) stack of java process($pid) under user($user)."
rm "$jstackFile" &>/dev/null
continue
}
Expand Down Expand Up @@ -582,7 +582,7 @@ main() {
tee ${append_file:+-a "$append_file"} ${store_dir:+-a "$store_file_prefix$PROG"} >/dev/null
((update_count != 1)) && headInfo

if [ "$cpu_sample_interval" == 0 ]; then
if [ "$cpu_sample_interval" = 0 ]; then
findBusyJavaThreadsByPs
else
findBusyJavaThreadsByTop
Expand Down
4 changes: 2 additions & 2 deletions bin/show-duplicate-java-classes
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ from glob import glob
from io import BytesIO
from optparse import OptionParser
from os import walk
from os.path import relpath, isdir, exists
from zipfile import ZipFile, BadZipfile
from os.path import exists, isdir, relpath
from zipfile import BadZipfile, ZipFile

################################################################################
# utils functions
Expand Down
1 change: 1 addition & 0 deletions bin/taoc
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ rotateColorPrint() {
}

rotateColorPrintln() {
# NOTE: $'foo' is the escape sequence syntax of bash
rotateColorPrint "$*"$'\n'
}

Expand Down
24 changes: 10 additions & 14 deletions bin/tcp-connection-state-counter
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ readonly PROG=${0##*/}
readonly PROG_VERSION='2.x-dev'

################################################################################
# util functions
# parse options
################################################################################

usage() {
cat <<EOF
Usage: ${PROG} [OPTION]...
Usage: $PROG [OPTION]...
show count of tcp connection stat.
Example:
${PROG}
$PROG
Options:
-h, --help display this help and exit
Expand All @@ -37,24 +37,20 @@ progVersion() {
exit
}

################################################################################
# parse options
################################################################################

for a; do
[[ "-h" == "$a" || "--help" == "$a" ]] && usage
done

for a; do
[[ "-V" == "$a" || "--version" == "$a" ]] && progVersion
args=("$@")
# check arguments in reverse, so last option wins.
for ((idx = $# - 1; idx >= 0; --idx)); do
[[ "${args[idx]}" = -h || "${args[idx]}" = --help ]] && usage
[[ "${args[idx]}" = -V || "${args[idx]}" = --version ]] && progVersion
done
unset args idx

################################################################################
# biz logic
################################################################################

# On MacOS, netstat need to using -p tcp to get only tcp output.
uname | grep Darwin -q && option_for_mac="-ptcp"
uname | grep Darwin -q && option_for_mac=-ptcp

# shellcheck disable=SC2086
netstat -tna ${option_for_mac:-} | awk 'NR > 2 {
Expand Down
20 changes: 10 additions & 10 deletions bin/uq
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ readonly PROG_VERSION='2.x-dev'
################################################################################

# NOTE: $'foo' is the escape sequence syntax of bash
readonly nl=$'\n' # new line
readonly NL=$'\n' # new line

redPrint() {
# if stdout is a terminal, turn on color output.
Expand Down Expand Up @@ -72,10 +72,10 @@ usage() {
(($# > 0)) && shift
local -r out=$(((exit_code != 0) + 1))

(($# > 0)) && redPrint "$*$nl" >&"$out"
(($# > 0)) && redPrint "$*$NL" >&"$out"

cat >&"$out" <<EOF
Usage: ${PROG} [OPTION]... [INPUT [OUTPUT]]
Usage: $PROG [OPTION]... [INPUT [OUTPUT]]
Filter lines from INPUT (or standard input), writing to OUTPUT (or standard output).
Same as \`uniq\` command in core utils,
but detect repeated lines that are not adjacent, no sorting required.
Expand Down Expand Up @@ -147,8 +147,8 @@ while (($# > 0)); do
uq_opt_all_repeated=1

uq_opt_repeated_method=${1#--all-repeated=}
[[ $uq_opt_repeated_method == 'none' || $uq_opt_repeated_method == 'prepend' || $uq_opt_repeated_method == 'separate' ]] ||
usage 1 "$PROG: invalid argument ‘${uq_opt_repeated_method}’ for ‘--all-repeated’${nl}Valid arguments are:$nl - ‘none’$nl - ‘prepend’$nl - ‘separate’"
[[ $uq_opt_repeated_method = 'none' || $uq_opt_repeated_method = 'prepend' || $uq_opt_repeated_method = 'separate' ]] ||
usage 1 "$PROG: invalid argument ‘$uq_opt_repeated_method’ for ‘--all-repeated’${NL}Valid arguments are:$NL - ‘none’$NL - ‘prepend’$NL - ‘separate’"

shift
;;
Expand Down Expand Up @@ -193,12 +193,12 @@ while (($# > 0)); do
esac
done

[[ $uq_opt_only_repeated == 1 && $uq_opt_only_unique == 1 ]] &&
[[ $uq_opt_only_repeated = 1 && $uq_opt_only_unique = 1 ]] &&
usage 2 "printing duplicated lines(-d, --repeated) and unique lines(-u, --unique) is meaningless"
[[ $uq_opt_all_repeated == 1 && $uq_opt_only_unique == 1 ]] &&
[[ $uq_opt_all_repeated = 1 && $uq_opt_only_unique = 1 ]] &&
usage 2 "printing all duplicate lines(-D, --all-repeated) and unique lines(-u, --unique) is meaningless"

[[ $uq_opt_all_repeated == 1 && $uq_opt_repeated_method == none && ($uq_opt_count == 0 && $uq_opt_only_repeated == 0) ]] &&
[[ $uq_opt_all_repeated = 1 && $uq_opt_repeated_method = none && ($uq_opt_count = 0 && $uq_opt_only_repeated = 0) ]] &&
yellowPrint "[$PROG] WARN: -D/--all-repeated=none option without -c/-d option, just cat input simply!" >&2

# DO NOT declare and assign var uq_max_input_size(as readonly) in ONE line!
Expand All @@ -217,7 +217,7 @@ elif ((argc == 1)); then
else
input_files=("${argv[@]:0:argc-1}")
output_file=${argv[argc - 1]}
if [ "$output_file" == - ]; then
if [ "$output_file" = - ]; then
output_file=/dev/stdout
fi
fi
Expand All @@ -226,7 +226,7 @@ readonly output_file
# Check input file
for f in ${input_files[@]:+"${input_files[@]}"}; do
# - is stdin, ok
[ "$f" == - ] && continue
[ "$f" = - ] && continue

[ -e "$f" ] || die "input file $f does not exist!"
[ ! -d "$f" ] || die "input file $f exists, but is a directory!"
Expand Down
Loading

0 comments on commit 4ad6b5b

Please sign in to comment.