I've got a few thousand small bam files produced against the exact same reference, and I want to merge them into one single big bam file. What is the best way to do that?

Should I do this iteratively or can I pass a long list of bam files to samtools/picard/etc in one go?

Edited, since this is now partially solved. In my terminal, the methods below works for up to 4092 files. More than that raises an error:

    samtools merge all.bam *.bam
    samtools merge all.bam `find /basedir/ -name "*myfiles*.bam"`
    samtools merge all.bam /basedir/*/???/*myfiles*.bam
Both are possible, but the second is probably best and easier

Put all your bam files in a folder (or create a folder with symbolic links to all sam files you want merge) and then

    samtools merge finalBamFile.bam *.bam

See [here][1]  for options about samtools (header and so on)

Editing to address the issue with many file.

You can take a three steps approach. 

First you print the header

    samtools view -H bar/foo/anyFile.bam > allSeq.sam

then you append sequences from all files using find

    find ./ -name \*.bam -exec samtools view {} \; >> allSeq.sam

and finally convert to bam

    samtools view -bh allSeq.sam > allSeq.bam

I can't quite test it at the moment, but should work

 [1]: http://samtools.sourceforge.net/samtools.shtml