I created a utility function to try to run 7z, then parse and construct a couple arrays of filenames and crcs from the output of 7z (which I want to use later in the function).
However, I'm getting weird behavior where, at the end of my function (currently - the function is still incomplete), when I try to use the bash syntax for expanding an array to all of its members, I just get the empty string.
Example of array expand syntax:
debuglog "z_filelist_name[@] = \"${z_filelist_name[@]}\""
That line results in output:
z_filelist_name[@] = ""
rmdupes()
{
debuglog "rmdupes: removing duplicates for archive $1"
#get list of files in archive from 7z
#local z_filelist_raw
declare -a z_filelist_name
declare -A z_filelist_crc
#z_filelist_raw=$(7z l -slt "$1")
i=0
#parse output of 7z to build array of filenames and checksums
7z l -slt "$1" | while read line
do
#possibly dangerous assumption in code below: For every Path, there will be a crc, thus, don't increment i until we find crc
debuglog "Processing line:"
debuglog "$line"
if [ "${line:0:6}" = "Path =" ]
then
z_filelist_name[$i]=$(echo $line | cut -d ' ' -f 3 )
debuglog "z_filelist_name[$i] = \"${z_filelist_name[$i]}\""
fi
if [ "${line:0:5}" = "CRC =" ]
then
#use bash associative array to associate filenames to crc values
z_filelist_crc[$z_filelist_name[$((i++))]]=$(echo $line | cut -d ' ' -f 3 )
fi
done
debuglog ""
debuglog "z_filelist_name[@] = \"${z_filelist_name[@]}\""
for zf in ${z_filelist_name[@]}
do
debuglog "Found Path (crc): $zf ( ${z_filelist_crc[$zf]} )"
done
}
Can anyone explain why the array values aren't being expanded properly. The debuglog statements earlier in the fuction that output individual elements by using the $i index variable, expand to the proper values.
Resolved by adding shopt -s lastpipe, as suggested in one of the answers to that question.
Well that's certainly an ugly shell programming semantic trap to fall into.
– JeffFromOhio Feb 06 '20 at 16:55