Skip to content

Instantly share code, notes, and snippets.

@qgp9
Created June 30, 2023 12:21
Show Gist options
  • Save qgp9/a5a43f3dcdad1c2d7c47ef22beb09a00 to your computer and use it in GitHub Desktop.
Save qgp9/a5a43f3dcdad1c2d7c47ef22beb09a00 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
function token_to_array() {
local -n array=$1
local str=$2
local i=0 c quote start=0
while [ $i -lt ${#str} ]; do
c=${str:$i:1}
case "$c" in
\\) i=$(( i + 1 ))
;;
\"|\'|\`)
[ -z "$quote" ] && quote=$c || { [ $quote = $c ] && quote=; }
;;
' '|\t)
if [ -z "$quote" ]; then
[ $start -lt $i ] && array+=("${str:$start:$(( i - start ))}")
start=$(( i + 1 ))
fi
;;
esac
i=$(( i + 1 ))
done
[ $start -lt ${#str} ] && array+=("${str:$start}")
}
function test1() {
local my_array
token_to_array my_array "$@"
declare -p my_array
}
#test1 "$@"
test1 ' 12 34 A="1 2" \"q '
test1 's 12 34 A="1 2" \"q q'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment