From ae9cf856455d3bd2bed0abcae621b0f75d222256 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sat, 15 Apr 2017 08:49:25 +0300 Subject: str_contains, str_*_with: proper escaping --- %HOME%/.bash_utils/text.sh | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to '%HOME%') diff --git a/%HOME%/.bash_utils/text.sh b/%HOME%/.bash_utils/text.sh index e27d392..f74fb23 100644 --- a/%HOME%/.bash_utils/text.sh +++ b/%HOME%/.bash_utils/text.sh @@ -76,6 +76,20 @@ str_toupper() ( done ) +escape_pattern() { + set -o errexit -o nounset -o pipefail + + local pattern + for pattern; do + pattern="${pattern//'\'/'\\'}" + pattern="${pattern//'*'/'\*'}" + pattern="${pattern//'?'/'\?'}" + pattern="${pattern//'['/'\['}" + pattern="${pattern//']'/'\]'}" + echo "$pattern" + done +} + str_contains() ( set -o errexit -o nounset -o pipefail @@ -88,8 +102,8 @@ str_contains() ( local sub="$2" [ -z "$sub" ] && return 0 + sub="$( escape_pattern "$sub" )" - sub="$( printf -- '%q' "$2" )" test "$str" != "${str#*$sub}" ) @@ -105,8 +119,8 @@ str_starts_with() ( local sub="$2" [ -z "$sub" ] && return 0 + sub="$( escape_pattern "$sub" )" - sub="$( printf -- '%q' "$sub" )" test "$str" != "${str#$sub}" ) @@ -122,8 +136,8 @@ str_ends_with() ( local sub="$2" [ -z "$sub" ] && return 0 + sub="$( escape_pattern "$sub" )" - sub="$( printf -- '%q' "$sub" )" test "$str" != "${str%$sub}" ) -- cgit v1.2.3