In bash
, you'd use readarray
to read the lines of a file or from the output of some command into an array; however that was only added in version 4.0 released in 2009, but macos still comes with bash 3.2.
macos comes with zsh though which is a much better shell.
To get the non-empty lines of the output of a command you'd split it with the f
parameter expansion flag (which splits on linef
eed), and to delete the "
(U+0022), “
(U+0201C) and ”
(U+201D) characters, use the ${var//pattern[/replacement]}
operator for instance:
#! /bin/zsh -
array=( ${(f)${"$(cmd)"//['"“”']}} ) || exit
If those are strings quoted with the U+0022 ASCII character and the quoting is compatible with the way quotes work in the zsh
language, you can also use its z
/Z
flag (to tokenise text the same way as the language parser does) and Q
flag (to remove quotes) instead of splitting by line (which would assume quoted strings can't span several lines).
#! /bin/zsh -
array=( ${(Q)${(Z[n])"$(cmd)"}} ) || exit
Your
declare -a array=(${tempvar})
in bash
uses the split+glob operator which is invoked when an expansion is left (usually unintentionally) unquoted. It splits the output on characters of the special $IFS
parameter (which by default in bash contains space, tab and newline) using a complex algorithm and the resulting words subject to globbing aka filename generation (which is hardly ever desirable).
Here, split+glob could be used to get you the non-empty lines of the output of your command, but you'd need to tune it first:
IFS=$'\n' # split on newline only:
set -o noglob # disable the glob part which we don't want
array=( $(cmd) ) # split+glob
Then you can remove the "“”
with ${var//pattern[/replacement]}
as well but in bash that has to be done in subsequently as it can't cumulate parameter expansion operators and the syntax (inherited from ksh93) is a bit more awkward:
array=( "${array[@]//['"“”']}" )
Note that contrary to the zsh
approach, that won't handle things like "foo \"bar\" and \\backslash"
.
U+201C LEFT DOUBLE QUOTATION MARK
andU+201D RIGHT DOUBLE QUOTATION MARK
quote characters like in your question or are they in reality the simple ASCII U+0022 QUOTATION MARK?