Skip to content

Instantly share code, notes, and snippets.

@mtongnz
Created January 9, 2024 23:19
Show Gist options
  • Select an option

  • Save mtongnz/b600c5651372fce23f355d9e23c80ccc to your computer and use it in GitHub Desktop.

Select an option

Save mtongnz/b600c5651372fce23f355d9e23c80ccc to your computer and use it in GitHub Desktop.
This is a script to extract and split the args in Bash using the User Scripts plugin. It allows for args that have spaces and are enclosed in double quotes.
#!/bin/bash
#description=Suck args into array
#argumentDescription=This is the description of the argument(s)
#argumentDefault="ab c dne" 1 2 "de" 3
splitArgs () {
# Default delimiter is *
if [ -z ${2+x} ]; then d=*; else d=$2; fi
# Set the IFS for splitting array
old=$IFS
IFS=$d
# Initial split by delimiter
args=${1//\" /\"$d}
args=(${args// \"/$d\"})
for key in "${!args[@]}"
do
val=${args[$key]}
if [[ ${args[$key]} == *'"'* ]]; then
# Strip leading & trailing double quote
val="${val%\"}"
args[$key]="${val#\"}"
else
# Split any remaining bits
a=("${args[@]:0:key}")
b=("${args[@]:key+1}")
v=(${val// /$d})
args=(${a[@]} ${v[@]} ${b[@]})
fi
done
# Reset the IFS
IFS=$old
}
# Display initial args
echo "ARGS: $1"
# Split it. You can set a second parameter as the delimiter
splitArgs "$1"
# Display all the args
for key in "${!args[@]}"
do
echo "arg$key:" ${args[$key]}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment