To append element(s) to an array in Bash, use += operator.
You can use: targets=($(grep -HRl "pattern" .)) Note use of (...) for array creation in BASH. Also you can use grep -l to get only file names in grep 's output (as shown in my command).
In order to convert a string into an array, please use
arr=($line)
or
read -a arr <<< $line
It is crucial not to use quotes since this does the trick.
Try this:
arr=(`echo ${line}`);
In: arr=( $line )
. The "split" comes associated with "glob".
Wildcards (*
,?
and []
) will be expanded to matching filenames.
The correct solution is only slightly more complex:
IFS=' ' read -a arr <<< "$line"
No globbing problem; the split character is set in $IFS
, variables quoted.
If you need parameter expansion, then try:
eval "arr=($line)"
For example, take the following code.
line='a b "c d" "*" *'
eval "arr=($line)"
for s in "${arr[@]}"; do
echo "$s"
done
If the current directory contained the files a.txt
, b.txt
and c.txt
, then executing the code would produce the following output.
a
b
c d
*
a.txt
b.txt
c.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With