awk '!x[$0]++' <<< "$list" | while read -r line; do array[count++]=$line done
O array
( itálico ) neste caso é uma parte do subshell
( negrito ).
O $line
e $array
tem um valor enquanto a subshell está viva, por assim dizer.
Quando o subshell terminar, também conhecido como dies, o ambiente pai (spawner) será restaurado. Isso inclui a obliteração de qualquer variável definida no subnível.
Neste caso:
-
$array
-
$line
Tente isto:
list=$'red apple\nyellow banana\npurple grape\norange orange\nyellow banana'
awk '!x[$0]++' <<< "$list" | while read -r line; do
array[count++]=$line
printf "array[%d] { %s\n" ${#array[@]} # array[num_of_elements] {
printf " %s\n" "${array[@]}" # elements
printf "}\n" # } end of array
done
printf "\n[ %s ]\n\n" "END OF SUBSHELL (PIPE)"
printf "array[%d] {\n" ${#array[@]}
printf " %s\n" "${array[@]}"
printf "}\n"
Rendimentos:
array[1] {
red apple
}
array[2] {
red apple
yellow banana
}
array[3] {
red apple
yellow banana
purple grape
}
array[4] {
red apple
yellow banana
purple grape
orange orange
}
[ END OF SUBSHELL (PIPE) ]
array[0] {
}
Ou como por manual.
Podemos começar com Pipelines
[…] Each command in a pipeline is executed in its own subshell (see Command Execution Environment). […]
E o Ambiente de Execução de Comando expande a aventura da seguinte forma:
[…] A command invoked in this separate environment cannot affect the shell’s execution environment.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell’s execution environment. […]
Não pode afetar: assim, não é possível definir.
No entanto, podemos redirecionar e fazer algo na direção de:
list=$'red apple\nyellow banana\npurple grape\norange orange\nyellow banana'
while read -r line; do
arr[count++]=$line
done <<<"$(awk '!x[$0]++' <<< "$list")"
echo "arr length = ${#arr[@]}"
count=0
while [[ $count -lt ${#arr[@]} ]]; do
echo ${arr[count++]}
done