Q:

Read a file line by line and run a java program

I need to run a java program that merge multiple files with a *bam extension. the structure of the program is:
java -jar mergefiles.jar \
I=file1.bam \
I=file2.bam \
I=file3.bam \
O=output.bam

So, I am trying the run this program for all *bam files in a directory. Initially, I try to create a list with the names of the *bam files (filenames.txt)
file1.bam
file2.bam
file3.bam

and using the 'while' command, like:
while read -r line; do
java -jar MergeFiles.jar \
I=$line \
O=output.bam
done < filenames.txt

However, the program executed for each *bam file in the text file but not all together (merge only one file per time, and overwrite the output). So, how I can run the program to merge all *bam files recursively?
Also, there are other option in the bash (e.g. using a loop for) to solve this issue?
Thanks in advance.

A:

In your question you specify that you would like to use all .bam files in a dir, so instead of creating a file with the filenames, you should probably use globbing instead. Here's an example:
#! /bin/bash
# set nullglob to be safe
shopt -s nullglob
# read the filenames into an array
files=( *.bam )
# check that files actually exist
if (( ${#files[@]} == 0 )); then echo "no files" && exit 1; fi
# expand the array with a replacement
java -jar MergeFiles.jar \
"${files[@]/#/I=}" \
O=output.bam

The problem with your current solution is that the while loop will only read one line at a time, calling the command on each line separately.

