This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How can I use getopts in a script that appends lines from files in a separate directory to a new file?

I am trying to write a bash script that takes in a directory, reads each file in the directory, and then appends the first line of each file in that directory to a new file. When I hard-code the variables in my script, it works fine.

This works:

#!/bin/bash

rm /local/SomePath/multigene.firstline.btab
touch /local/SomePath/multigene.firstline.btab

btabdir=/local/SomePath/test/*
outfile=/local/SomePath/multigene.firstline.btab

for f in $btabdir
do
    head -1 $f >> $outfile
done

This does not work:

#!/bin/bash

while getopts ":d:o:" opt; do
  case ${opt} in
    d) btabdir=$OPTARG;;
    o) outfile=$OPTARG;;
  esac
done

rm $outfile
touch $outfile

for f in $btabdir
do
    head -1 $f >> $outfile
done

Here is how I call the script:

bash /local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh -d /local/SomePath/test/* -o /local/SomePath/out.test/multigene.firstline.btab

And here is what I get when I run it:

rm: missing operand
Try 'rm --help' for more information.
touch: missing file operand
Try 'touch --help' for more information.
/local/SomePath/Scripts/btab.besthits.wBp-q_wBm-r.sh: line 23: $outfile: ambiguous redirect

Any suggestions? I'd like to be able to use getopts so I can make the script more generic. Thanks!

alignment software error

Why not something like:

head -n1 -q /local/SomePath/test/* >> /local/SomePath/out.test/multigene.firstline.btab

This is so simple. Thanks!

0 answers

No answers yet.

Log in to answer this question.