samtools fastq can convert bam to fastq format, e.g. samtools fastq input.bam -o output.fastq
The output file will be automatically compressed if the file names have a .gz or .bgzf extension, e.g.
samtools fastq input.bam -o output1.fastq.gz
Alternatively, you can also pipe the stdout to compressor explicitly, e.g.
samtools fastq input.bam | gzip > output2.fastq.gz
Interestingly, I noticed that output2.fastq.gz is significantly smaller than output1.fastq.gz, even though the uncompressed file content is the same.
Actually, this is because of the different default compression ratio used in samtools and gzip.
In samtools fastq, its default compression level is 1 (out of [0..9]) while gzip's default compression level is 6 (out of [1..9]).