Skip to content

Commit

Permalink
refactor/robust(c): use printf πŸ’ͺ instead of echo; use if-else…
Browse files Browse the repository at this point in the history
… instead of `&&-||`

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
  • Loading branch information
oldratlee committed Aug 28, 2023
1 parent 84b6218 commit 59044e2
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions bin/c
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ readonly PROG_VERSION='2.5.0-dev'
# util functions
################################################################################

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 "$*"
printErrorMsg() {
# check isatty in bash https://stackoverflow.com/questions/10022323
# if stdout is console, print with red color.
if [ -t 1 ]; then
printf "\033[1;31m%s\033[0m\n\n" "Error: $*"
else
printf '%s\n\n' "Error: $*"
fi
}

usage() {
Expand All @@ -49,7 +51,7 @@ usage() {
# shellcheck disable=SC2015
[ "$exit_code" != 0 ] && local -r out=/dev/stderr || local -r out=/dev/stdout

(($# > 0)) && redEcho "$*$nl" >$out
(($# > 0)) && printErrorMsg "$*" >$out

cat >$out <<EOF
Usage: ${PROG} [OPTION]... [command [command_args ...]]
Expand All @@ -73,7 +75,7 @@ EOF
}

progVersion() {
echo "$PROG $PROG_VERSION"
printf '%s\n' "$PROG $PROG_VERSION"
exit
}

Expand Down Expand Up @@ -106,7 +108,7 @@ while [ $# -gt 0 ]; do
break
;;
-*)
usage 2 "${PROG}: unrecognized option '$1'"
usage 2 "unrecognized option '$1'"
;;
*)
# if not option, treat all follow args as command
Expand Down

0 comments on commit 59044e2

Please sign in to comment.