Skip to content

Commit a17b7c2

Browse files
committed
refactor/robust(cp-into-docker-run): use printf 💪 instead of echo; use if-else instead of &&-||; improve portability(portableReadLink)
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
1 parent 7d166fe commit a17b7c2

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

bin/cp-into-docker-run

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,17 @@ readonly PROG_VERSION='2.5.0-dev'
1717
# util functions
1818
################################################################################
1919

20-
# NOTE: $'foo' is the escape sequence syntax of bash
21-
readonly ec=$'\033' # escape char
22-
readonly eend=$'\033[0m' # escape end
23-
readonly nl=$'\n' # new line
24-
25-
redEcho() {
20+
redPrint() {
2621
# -t check: is a terminal device?
27-
[ -t 1 ] && echo "${ec}[1;31m$*$eend" || echo "$*"
22+
if [ -t 1 ]; then
23+
printf "\033[1;31m%s\033[0m\n" "$*"
24+
else
25+
printf '%s\n' "$*"
26+
fi
2827
}
2928

3029
die() {
31-
redEcho "Error: $*" 1>&2
30+
redPrint "Error: $*" 1>&2
3231
exit 1
3332
}
3433

@@ -47,10 +46,15 @@ portableReadLink() {
4746
readlink -f "$file"
4847
;;
4948
Darwin*)
49+
local py_args=(-c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$file")
5050
if command -v greadlink >/dev/null; then
5151
greadlink -f "$file"
52+
elif command -v python3 >/dev/null; then
53+
python3 "${py_args[@]}"
54+
elif command -v python >/dev/null; then
55+
python "${py_args[@]}"
5256
else
53-
python -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$file"
57+
die "fail to find command(greadlink/python3/python) for readlink!"
5458
fi
5559
;;
5660
*)
@@ -65,7 +69,9 @@ usage() {
6569
# shellcheck disable=SC2015
6670
[ "$exit_code" != 0 ] && local -r out=/dev/stderr || local -r out=/dev/stdout
6771

68-
(($# > 0)) && redEcho "$*$nl" >$out
72+
# NOTE: $'foo' is the escape sequence syntax of bash
73+
local nl=$'\n' # new line
74+
(($# > 0)) && redPrint "$*$nl" >$out
6975

7076
cat >$out <<EOF
7177
Usage: ${PROG} [OPTION]... command [command-args]...
@@ -100,7 +106,7 @@ EOF
100106
}
101107

102108
progVersion() {
103-
echo "$PROG $PROG_VERSION"
109+
printf '%s\n' "$PROG $PROG_VERSION"
104110
exit
105111
}
106112

@@ -235,7 +241,7 @@ trap cleanupWhenExit EXIT
235241
########################################
236242

237243
logAndRun() {
238-
$verbose && echo "[$PROG] $*" 1>&2
244+
$verbose && printf '%s\n' "[$PROG] $*" 1>&2
239245
"$@"
240246
}
241247

0 commit comments

Comments
 (0)