How can I use getopts in a script that appends lines from files in a separate directory to a new file?
0
0
Entering edit mode
4.2 years ago
Digsby ▴ 10

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 • 667 views
ADD COMMENT
0
Entering edit mode

Why not something like:

head -n1 -q /local/SomePath/test/* >> /local/SomePath/out.test/multigene.firstline.btab
ADD REPLY
0
Entering edit mode

This is so simple. Thanks!

ADD REPLY

Login before adding your answer.

Traffic: 2711 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6