0

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.

  • 2
    I believe this is a duplicate of https://unix.stackexchange.com/questions/9954/why-is-my-variable-local-in-one-while-read-loop-but-not-in-another-seemingly; see also https://unix.stackexchange.com/questions/272698/why-is-the-array-empty-after-the-while-loop?noredirect=1&lq=1 – Jeff Schaller Feb 06 '20 at 16:43
  • Thank you. Yes, turns out this is a pipeline subshell with variable assignment issue, as detailed in the first link at @JeffSchaller provided.

    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

0 Answers0