From b2a6bb6e457d39a93a928c15a55f8f6931d7298c Mon Sep 17 00:00:00 2001 From: Jerry Lee Date: Wed, 30 Aug 2023 13:58:55 +0800 Subject: [PATCH] =?UTF-8?q?refactor/robust(`uq`):=20use=20`printf`=20?= =?UTF-8?q?=F0=9F=92=AA=20instead=20of=20`echo`;=20use=20`if-else`=20inste?= =?UTF-8?q?ad=20of=20`&&-||`;=20use=20`${var#}`=20instead=20of=20`awk`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NOTE: - the `echo` option(e.g. -e -n) may effect correctness, `printf` is more robust 💪 - about `&&-||` see shell check: https://www.shellcheck.net/wiki/SC2015 --- bin/uq | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/bin/uq b/bin/uq index f7b2ebee..bdb59914 100755 --- a/bin/uq +++ b/bin/uq @@ -38,20 +38,28 @@ readonly PROG_VERSION='2.5.0-dev' ################################################################################ # NOTE: $'foo' is the escape sequence syntax of bash -readonly ec=$'\033' # escape char -readonly eend=$'\033[0m' # escape end -readonly nl=$'\n' # new line - -redEcho() { - [ -t 1 ] && echo "${ec}[1;31m$*$eend" || echo "$*" +readonly nl=$'\n' # new line + +redPrint() { + # -t check: is a terminal device? + if [ -t 1 ]; then + printf "\033[1;31m%s\033[0m\n" "$*" + else + printf '%s\n' "$*" + fi } -yellowEcho() { - [ -t 1 ] && echo "${ec}[1;33m$*$eend" || echo "$*" +yellowPrint() { + # -t check: is a terminal device? + if [ -t 1 ]; then + printf "\033[1;33m%s\033[0m\n" "$*" + else + printf '%s\n' "$*" + fi } die() { - redEcho "Error: $*" 1>&2 + redPrint "Error: $*" 1>&2 exit 1 } @@ -82,7 +90,7 @@ usage() { # shellcheck disable=SC2015 [ "$exit_code" != 0 ] && local -r out=/dev/stderr || local -r out=/dev/stdout - (($# > 0)) && redEcho "$*$nl" >$out + (($# > 0)) && redPrint "$*$nl" >$out cat >$out < 0)); do --all-repeated=*) uq_opt_all_repeated=1 - uq_opt_repeated_method=$(echo "$1" | awk -F= '{print $2}') + 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’" @@ -209,7 +217,7 @@ done 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) ]] && - yellowEcho "[$PROG] WARN: -D/--all-repeated=none option without -c/-d option, just cat input simply!" >&2 + yellowPrint "[$PROG] WARN: -D/--all-repeated=none option without -c/-d option, just cat input simply!" >&2 # NOTE: DO NOT declare var uq_max_input_size as readonly in ONE line! uq_max_input_size="$(convertHumanReadableSizeToSize "$uq_max_input_human_readable_size")" ||