Home > OS >  Bash script appending existing array element to array in loop splitting on space (whitespace?)
Bash script appending existing array element to array in loop splitting on space (whitespace?)

Time:05-16

Can someone please tell me why it is splitting my value into two array elements upon appending to a new array?

Here is my code, with output below...

#!/bin/bash
IFS=$'\r\n' GLOBIGNORE='*' command eval  'toexec=($(cat /root/devops/commands.txt))'
#printf '%s\n' "${toexec[@]}"
dirlist=(`ls /root/devops/files/*`)
toCompress=()
toOutput=()
for fileList in ${dirlist[*]}
do
  toOutput =($(basename ${fileList}));
  toCompress =("${fileList}"$'\n');
done
newOut=()
printf '%s\n' "${toexec[@]}"
for (( i=0; i<${#toexec[@]}; i   ));
do
    newval="${toexec[$i]},${toOutput[$i]}"$'\n';
    newOut =($newval);
done
echo "======"
printf '%s\n' "${newOut[@]}"

Here is the output, separated by =====, existing array on top, new array on bottom. As you can see, it is putting each element into two elements, splitting on the single space between gzip and its option,filename, for example gzip and -1,a.txt.

OUTPUT

gzip -1
gzip -9
======
gzip
-1,a.txt
gzip
-9,b.txt
...
==debug additional info==
--toexec < commands.txt--
gzip -1
gzip -9
=========================
--toCompress < ls--------
=========================
/root/devops/files/a.txt

/root/devops/files/b.txt

----toOutput-------------
a.txt
b.txt
=========================
----newOut---------------
gzip
-1,a.txt
gzip
-9,b.txt
=========================

CodePudding user response:

Because the value is not double quoted, as in

newOut =("$newval")

That would add a single element to the array.

  • Related