Skip to content

Commit

Permalink
refactor: use BASH_SOURCE array to detect whether this script is so…
Browse files Browse the repository at this point in the history
…urced or not 🕵️
  • Loading branch information
oldratlee committed Nov 22, 2023
1 parent 3b92d9d commit fde4a18
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions lib/console-text-color-themes.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ if command -v greadlink >/dev/null; then
_ctct_READLINK_CMD=greadlink
fi

# NOTE: DO NOT declare var _ctct_PROG as readonly in ONE line!
_ctct_PROG="$(basename -- "$($_ctct_READLINK_CMD -f -- "${BASH_SOURCE[0]}")")"
[ "$_ctct_PROG" == 'console-text-color-themes.sh' ] && readonly _ctct_is_direct_run=true

readonly _ctct_ec=$'\033' # escape char
readonly _ctct_eend=$'\033[0m' # escape end

Expand All @@ -55,9 +51,10 @@ colorEchoWithoutNewLine() {
fi
}

# if not directly run this script(use as lib), just export 2 helper functions,
# and do NOT print anything.
[ "$_ctct_is_direct_run" == true ] && {
# if not directly run this script(use as lib), just export 2 helper functions, and do NOT print anything.
#
# if directly run this script, the length of array BASH_SOURCE is 1.
if ((${#BASH_SOURCE[@]} == 1)); then
for style in 0 1 2 3 4 5 6 7; do
for fg in 30 31 32 33 34 35 36 37; do
for bg in 40 41 42 43 44 45 46 47; do
Expand Down Expand Up @@ -97,4 +94,4 @@ colorEchoWithoutNewLine() {
echo 'Output of above code:'
echo -n ' '
colorEcho '1;36;41' 'Sample Text'
}
fi

0 comments on commit fde4a18

Please sign in to comment.