Skip to content

Commit 681bfdb

Browse files
committed
Add improved bash key-val parser. Non eval version
1 parent 1645851 commit 681bfdb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

func/main.sh

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,32 @@ is_object_valid() {
246246
fi
247247
}
248248

249+
# Check if a object string with key values pairs has the correct format and load it afterwards
250+
parse_object_kv_list_non_eval() {
251+
local str
252+
local objkv obj_key obj_val
253+
local OLD_IFS="$IFS"
254+
255+
str=${@//$'\n'/ }
256+
str=${str//\"/\\\"}
257+
str=${str//$/\\$}
258+
IFS=$'\n'
259+
260+
# Extract and loop trough each key-value pair. (Regex test: https://regex101.com/r/eiMufk/5)
261+
for objkv in $( echo "$str" | perl -n -e "while(/\b([a-zA-Z]+[\w]*)='(.*?)'(\s|\$)/g) {print \$1.'='.\$2 . \"\n\" }" ); do
262+
263+
if ! [[ "$objkv" =~ ^([[:alnum:]][_[:alnum:]]{0,64}[[:alnum:]])=(\'?[^\']+?\'?)?$ ]]; then
264+
check_result $E_INVALID "Invalid key value format [$objkv]"
265+
fi
266+
267+
obj_key=${objkv%%=*} # strip everything after first '=' char
268+
obj_val=${objkv#*=} # strip everything before first '=' char
269+
declare -g $obj_key="$obj_val"
270+
271+
done
272+
IFS="$OLD_IFS"
273+
}
274+
249275
# Check if a object string with key values pairs has the correct format and load it afterwards
250276
parse_object_kv_list() {
251277
local str

0 commit comments

Comments
 (0)