0

I'm a novice in bash scripting. I wrote a script that concatenates many files from different directories into large files

#!/bin/bash
for f in foo/$1/*; do
    if [ -d "$f" ]; then
        for d in $f/*; do
                if [ -d "$d" ]; then
                file=$( echo ${d##*/} )
                mkdir -p bar/$1/"$file"/fastq/
                cat $d/*/fastq_pass/* >> bar/$1/"$file"/fastq/$file.fastq.gz
                        fi
                done
    fi
done

I've noticed that some of merged files lost 1-2 GB in size, which is weird because other files are ok. When I tried to do

cat foo/* >> bar/largefile.fastq.gz

there was no loss. So it's definitely because of my script. Where's error?

6
  • Not an answer to your question but you cannot create a new valid .gz file by concatenating several smaller files together.
    – doneal24
    Aug 25, 2021 at 13:49
  • 1
    @doneal24, why not? i've concatenated small gz files to a large gz several times manually with cat
    – Daniyar
    Aug 25, 2021 at 14:25
  • 1
    @doneal24 Yes you can. It's a feature of the gzip format (and of the bzip2 and xz formats too, actually).
    – Kusalananda
    Aug 25, 2021 at 14:30
  • 3
    How do you measure the file sizes and how do you determine that the files shrink?
    – Kusalananda
    Aug 25, 2021 at 18:11
  • @Kusalananda, after running the script, I measured the size using du -sc of multiple files in the source directory and the large file in the destination directory. Then, I manually run cat, after which repeated with du -sc. I noticed that the file after script is less in size than after manual cat
    – Daniyar
    Aug 26, 2021 at 6:41

1 Answer 1

-1

For efficiency, filesystems allocate disk space in clusters of blocks. Thus, a "1 byte" file would be allocated a whole cluster. Concatenating 100 "1 byte" files, producing 100 bytes of data would still take a single cluster.

Cluster and block sizes can vary, there's a subfield of Performance Analysis dedicated to optimizing for a particular application.

1
  • so how to edit my code so that cat would concatenate files without loss? because when I run cat independently for one direction, it works fine
    – Daniyar
    Aug 25, 2021 at 17:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .