My goal is to split a string into an array and if the second parameter of the function is not 1, remove the first element of the array. Return string which could be literal for array assignment.
#!/usr/bin/env bats
log_debug() {
echo "$@" >> /dev/stderr
}
split_line() {
rmfirst=${2:-0}
log_debug "args: \"$1\", ${rmfirst}"
read -ra out_arr <<< "$1"
log_debug "out: $(declare -p out_arr)"
if [ $rmfirst -ne 1 ] ; then
unset "out_arr[0]"
fi
echo "${out_arr[@]}"
}
@test "split line" {
line_arr=("$(split_line "GETINFO version")")
[ "${line_arr[0]}" = "version" ]
}
@test "split line rmfirst" {
line_arr=("$(split_line "GETINFO version" 0)")
[ "${line_arr[0]}" = "version" ]
}
@test "split line no-rmfirst" {
IFS=" " line_arr=("$(split_line "GETINFO version" 1)")
[[ "$(declare -p line_arr)" == 'declare -'[aA]* ]]
log_debug "$(declare -p line_arr)"
[[ "${line_arr[0]}" == "GETINFO" ]]
[[ ${#line_arr} -eq 2 ]]
[[ "${line_arr[1]}" == "version" ]]
}
but when I run the test fails:
✓ split line
✓ split line rmfirst
✗ split line no-rmfirst
(in test file tests/foundational.bats, line 39)
`[[ "${line_arr[0]}" == "GETINFO" ]]' failed
args: "GETINFO version", 1
out: declare -a out_arr=([0]="GETINFO" [1]="version")
declare -a line_arr=([0]="GETINFO version")
3 tests, 1 failure
Any idea, what’s wrong with my function?
You need to remove double quotes from line_arr
to make it an array:
IFS=" " line_arr=($(split_line "GETINFO version" 1))