Skip to content

Commit 592719e

Browse files
committed
refactor/robust(bump-scripts-version.sh) 💪 : fix Bash Pitfalls No.1/No.5; use printf instead of echo
1 parent 02588c9 commit 592719e

File tree

1 file changed

+27
-26
lines changed

1 file changed

+27
-26
lines changed

test-cases/bump-scripts-version.sh

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,30 @@ set -eEuo pipefail
55
# util functions
66
################################################################################
77

8-
# NOTE: $'foo' is the escape sequence syntax of bash
9-
readonly ec=$'\033' # escape char
10-
readonly eend=$'\033[0m' # escape end
11-
readonly nl=$'\n' # new line
8+
readonly nl=$'\n' # new line
129

13-
colorEcho() {
14-
local color=$1
10+
colorPrint() {
11+
local color="$1"
1512
shift
16-
17-
# if stdout is the console, turn on color output.
18-
[ -t 1 ] && echo "${ec}[1;${color}m$*${eend}" || echo "$*"
13+
# check isatty in bash https://stackoverflow.com/questions/10022323
14+
# if stdout is console, turn on color output.
15+
if [ -t 1 ]; then
16+
printf "\033[1;${color}m%s\033[0m\n" "$*"
17+
else
18+
printf '%s\n' "$*"
19+
fi
1920
}
2021

21-
redEcho() {
22-
colorEcho 31 "$@"
22+
redPrint() {
23+
colorPrint 31 "$@"
2324
}
2425

25-
yellowEcho() {
26-
colorEcho 33 "$@"
26+
yellowPrint() {
27+
colorPrint 33 "$@"
2728
}
2829

29-
blueEcho() {
30-
colorEcho 36 "$@"
30+
bluePrint() {
31+
colorPrint 36 "$@"
3132
}
3233

3334
logAndRun() {
@@ -41,13 +42,13 @@ logAndRun() {
4142
echo "Run under work directory $PWD : $*"
4243
"$@"
4344
else
44-
blueEcho "Run under work directory $PWD :$nl$*"
45+
bluePrint "Run under work directory $PWD :$nl$*"
4546
time "$@"
4647
fi
4748
}
4849

4950
die() {
50-
redEcho "Error: $*" 1>&2
51+
redPrint "Error: $*" 1>&2
5152
exit 1
5253
}
5354

@@ -59,13 +60,13 @@ die() {
5960
readonly bump_version="$1"
6061

6162
# adjust current dir to project dir
62-
cd "$(dirname "$(readlink -f "$0")")/.."
63-
64-
script_files=$(
65-
find bin legacy-bin -type f
66-
)
63+
#
64+
# Bash Pitfalls#5
65+
# http://mywiki.wooledge.org/BashPitfalls#cd_.24.28dirname_.22.24f.22.29
66+
cd -P -- "$(dirname -- "$0")"/..
6767

68-
# shellcheck disable=SC2086
69-
logAndRun sed -ri \
70-
's/^(.*PROG_VERSION\s*=\s*)'\''(.*)'\''(.*)$/\1'\'"$bump_version"\''\3/' \
71-
$script_files
68+
# Bash Pitfalls#1
69+
# http://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29
70+
logAndRun find -D exec bin legacy-bin lib -type f -exec \
71+
sed -ri "s/^(.*\bPROG_VERSION\s*=\s*')\S*('.*)$/\1$bump_version\2/" -- \
72+
{} +

0 commit comments

Comments
 (0)