I don't understand why this example script doesn't modify the contents of array2. It seems that we should be able to set array2 to be equal to array1 by iterating through array1's elements and setting the corresponding element by index of array2 to be equal to the element in array1
#!/bin/bash
array1=(1 2 3)
array2=()
modify_array2 () {
#set array2 to be equal to array1 by iterating through array1's
#elements and setting the corresponding element by index of array2 by
#to be equal to the element in array1
index=0
declare -a _array1=("${!1}")
declare -a _array2=("${!2}")
for i in "${_array1[@]}"; do
_array2["$index"]="$i"
((index++))
done
}
modify_array2 array1[@] array2[@]
#this should permanently modify array2, however if we print the
#contents of array2, we get nothing:
for i in "${array2[@]}"; do
printf "$i\n"
done
output:
Shellcheck says the following:
Line 3: array1=(1 2 3) ^-- SC2034: array1 appears unused. Verify use (or export if used externally). Doesnt make sense, I'm clearly using it in:
modify_array2 array1[@] array2[@]
Line 11: _array2["$index"]="$i" ^-- SC2034: _array2 appears unused. Verify use (or export if used externally).
odd, because aren't I using it by expanding by using a positional parameter in:
modify_array2 array1[@] array2[@]
and also using in the function in:
_array2["$index"]="$i"
Line 19: printf "$i\n" ^-- SC2059: Don't use variables in the printf format string. Use printf "..%s.." "$foo".
Fine, but I tried echo as well, same result