Switch to converting to an array directly.

This eliminates the the middle step of converting to a string with a different IFS which should be more efficient.
This commit is contained in:
Tom Alexander 2023-07-18 17:10:31 -04:00
parent 0c23b46426
commit b9a199c5f5
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
1 changed files with 7 additions and 10 deletions

View File

@ -23,7 +23,7 @@ function log {
############## Program #########################
function main {
VMS=($(convert_ifs "$VMS" ' ' "$IFS"))
convert_to_array 'VMS'
local snapshot_name="$1"
local rollback_targets=$(doas zfs list -t snapshot -p -o name | grep -E "@${snapshot_name}\$")
@ -65,20 +65,17 @@ function sanity_check_targets {
done<<<"$rollback_targets"
}
function convert_ifs {
# Converts a string from one internal field separator to another. For example "foo bar baz" to "foo:bar:baz". This is useful for parsing a string as an array (for example, to read the value from environment variables like $PATH) while using a different IFS
function convert_to_array {
# Converts a string separated by a value into an array. An example use-case would be for parsing environment variables like $PATH.
#
# TODO: It would be a lot better if we could just convert from string to array directly using a temporarily different IFS variable without converting to a different string format first.
local string_to_convert="$1"
local ifs_in_string="$2"
local target_ifs="$3"
# WARNING: This uses nameref to modify the env variable at the first parameter, making this function very much not "functional". It does not return anything on stdout so it cannot be used with $().
local -n string_to_convert="$1"
local ifs_in_string="${2:- }"
local current_ifs="$IFS"
IFS="$ifs_in_string"
local split_to_array=($string_to_convert)
local expanded_string=$(IFS="$target_ifs"; printf '%s' "${split_to_array[*]}")
string_to_convert=($string_to_convert)
# Restore IFS to the original value in case this function is not run inside a subshell
IFS="$current_ifs"
cat <<<"$expanded_string"
}
main "$@"