Você deve usar printf
em vez de echo
:
printf "%s\n" "${mtches[@]}"
Se mtches
estiver vazio, isso ainda produzirá uma linha vazia. Para explicar isso:
{ [ "${#mtches[@]}" -eq 0 ] || printf '%s\n' "${mtches[@]}"; } > file
Em bash
(e também POSIX shells), você costuma usar matriz de Parâmetros Posicionais como "$@"
em vez de "$*"
, a menos que você tenha um motivo especial. Isso também é verdade em shells que suportam arrays regulares , de man bash - section Arrays :
Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell’s filename expansion operators. If the subscript is ‘@’ or ‘*’, the word expands to all members of the array name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters ‘@’ and ‘*’
Use somente "${array[*]}"
quando quiser unir todos os elementos do array a uma string.