commit: f77a397df8c2a623a296600ee38a01dbdd98933b
Author: Kerin Millar <kfm <AT> plushkava <DOT> net>
AuthorDate: Sat Aug 17 15:42:41 2024 +0000
Commit: Sam James <sam <AT> gentoo <DOT> org>
CommitDate: Thu Aug 22 19:37:46 2024 +0000
URL:
https://gitweb.gentoo.org/proj/gentoo-functions.git/commit/?id=f77a397d
Optimise trim() for bash where processing the positional parameters
Render trim() faster in bash for cases where only the positional
parameters are to be processed e.g. var=$(trim "$var") or
var=${ trim "$var"; }.
Signed-off-by: Kerin Millar <kfm <AT> plushkava.net>
functions.sh | 19 ++++++++++++++-----
1 file changed, 14 insertions(+), 5 deletions(-)
diff --git a/functions.sh b/functions.sh
index bd96df6..3dd2969 100644
--- a/functions.sh
+++ b/functions.sh
@@ -650,12 +650,21 @@ srandom()
#
trim()
{
- if [ "$#" -gt 0 ]; then
- printf '%s\n' "$@"
+ local arg
+
+ if [ "$#" -gt 0 ] && [ "${BASH}" ]; then
+ for arg; do
+ eval '[[ ${arg} =~ ^[[:space:]]+ ]] &&
arg=${arg:${#BASH_REMATCH}}'
+ eval '[[ ${arg} =~ [[:space:]]+$ ]] &&
arg=${arg:0:${#arg} - ${#BASH_REMATCH}}'
+ printf '%s\n' "${arg}"
+ done
else
- cat
- fi |
- sed -e 's/^[[:space:]]\{1,\}//' -e 's/[[:space:]]\{1,\}$//'
+ if [ "$#" -gt 0 ]; then
+ printf '%s\n' "$@"
+ else
+ cat
+ fi | sed -e 's/^[[:space:]]\{1,\}//' -e 's/[[:space:]]\{1,\}$//'
+ fi
}
#