I’m tempted to close this as it’s really just a programming question, unless you can rephrase it somehow, but I got started with the answer so here it is:
getopt looks fine. You just need to use the variables assigned in the
case switch downstream. What you will need to do however is pass an array of files. At present, getopt is only taking in one file at a time. This can get tricky.
-b because that is the first argument in your command. Once you’ve parsed with
getopt, you shouldn’t touch the standard argv style variables any more (other than maybe
$0 if you want to get the script name).
bash script.sh -b somefile.ext -c someoption
^ ^ ^ ^ ^
$0 $1 $2 $3 $4
This is why you see all of your arguments when you do
for i in $@.
Here’s one way of handling multiple inputs to the same argument:
while getopts "hi:m:o:" OPTION ; do
case $OPTION in
i) ID+=($OPTARG) ;; # appends an array rather than set a single variable
m) mode=$OPTARG ;;
o) outdir=$OPTARG ;;
h) usage && exit 1 ;;
shift $((OPTIND -1))
(From my code at: https://github.com/jrjhealey/bioinfo-tools/blob/master/getpdb.sh#L47-L55 )
Notice the use of
+= instead of just
= for the
i variable as an incremented array of files which can be looped through.
This is slightly different, as I’m iterating a set of strings, and that list is unlikely ever to be very long, so (annoyingly) they all need the
-i flag each time (until i can be bothered to rewrite it perhaps). This ensures they’re all added to the array which corresponds to the IDs in question.
With a wildcard expanded list of files, you will probably want to treat it as a positional argument to come last, which will mean you don’t have to worry about capturing any other optional arguments after the files. It also means you wont need an dash-option before each one.
In which case, you’ll need to iterate through all the commandline arguments, capturing any options (which is what getopt is doing). Once you’ve parsed all of those, everything left in
$@ should be your filenames which you can loop over as you’re about to do. The secret to this likes in
OPTIND, the index of the arguments on the commandline. You need only find the first index which matches a file name, then gather all of the arguments from there to the end of the command in to an array (or carry on using
$@. Passing a prexisting directory of bam files and parsing the output of a
find command or similar would be much easier, if a little less user friendly.
If you aren’t sure what your commands in the loop should be, figure it out for a single file first. I would write separate functions for calculating the number of reads, and basically compartmentalise each step.