I'm trying to create a #!/bin/sh compatible string_split function that has a similar command syntax to the read command so that you can pass in the string you want to split and the variables you want to assign the strings too.
This is the function I've come up with, but I can't figure out how to make the new values available outside of the function like the read command can.
#!/bin/sh
split_str() {
input_original=$1
input=$1
input_delimiter=$2
input=$(echo "$input" | sed -e "s/$input_delimiter/ /g")
set -- "$input_original" "$input_delimiter" $input
}
The desired command use would look like this:
split_str "Hello World" " " word1 word2
echo "$word1"
# Output: Hello
echo "$word2"
# Output: World
Solution
Using bac0ns answer below I was able to get this solution which works with any number of output parameters passed. Thanks for the help @bac0n
#!/bin/sh
split_str() {
input=$1
input_delimiter=$2
# Isolate the output parameters
output_params=$(echo "${@}" | sed -e "s/$input $input_delimiter//g")
# Add an extra variable argument to catch any overflow.
# This prevents any extra parts of the sub string from being added to the
# passed parameters.
output_params="$output_params overflow"
# Split the string by reading the values in with read
IFS="$input_delimiter" read -r $output_params << EOF
$1
EOF
}