Skip to content

Commit

Permalink
refactor/robust(echo-args): use printf 💪 instead of echo; align…
Browse files Browse the repository at this point in the history
… the index number
  • Loading branch information
oldratlee committed Sep 3, 2023
1 parent 1dcead5 commit ddb91c7
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions bin/echo-args
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,37 @@
# @author Jerry Lee (oldratlee at gmail dot com)
set -eEuo pipefail

readonly ec=$'\033' # escape char
readonly eend=$'\033[0m' # escape end
digitCount() {
# argument 1(num) is always a non-negative integer in this script usage,
# so NO argument validation logic.
local num="$1" count=0
while ((num != 0)); do
((++count))
((num = num / 10))
done
echo "$count"
}

digit_count=$(digitCount $#)
readonly arg_count=$# digit_count

readonly red='\033[1;31m'
readonly blue='\033[1;36m'
readonly normal='\033[0m'

echoArg() {
local index="$1" count="$2" value="$3"
printArg() {
local idx="$1" value="$2"

# if stdout is console, turn on color output.
[ -t 1 ] &&
echo "${index}/${count}: ${ec}[1;31m[$eend${ec}[1;36;40m$value$eend${ec}[1;31m]$eend" ||
echo "${index}/${count}: [${value}]"
if [ -t 1 ]; then
printf "%${digit_count}s/%s: ${red}[${blue}%s${red}]${normal}\n" "$idx" "$arg_count" "$value"
else
printf "%${digit_count}s/%s: [%s]\n" "$idx" "$arg_count" "$value"
fi
}

echoArg 0 $# "$0"
printArg 0 "$0"
idx=1
for a; do
echoArg $((idx++)) $# "$a"
printArg $((idx++)) "$a"
done

0 comments on commit ddb91c7

Please sign in to comment.