BillPull
BillPull

Reputation: 7013

Parsing arguments/options/flags in a bash script

I am trying to parse an option in a bash script. how can I use getopts to see whether an optional flag has been entered.

FILE1=$1
FILE2=$2
outputfile=''
while getopts "o" OPTION
do
    case $OPTION in
    o)
       outputfile=$OPTARG
    ;;
    esac
done
if [ ! $outputfile -eq '' ]
then
    cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n" | paste $FILE1 $FILE2 | tr '\t' '\n' > $outputfile

else
    cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n" 
    paste $FILE1 $FILE2 | tr '\t' '\n' 
fi

Upvotes: 1

Views: 3745

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 125708

There are a number of problems here. You need to parse options (the getopts loop) first, then remove them from the argument list (with shift $(($OPTIND-1))), then get FILE1 and FILE2 from $1 and $2. Second, you need to tell getopts that -o takes an argument (getopts "o:"). Third, your getopts loop should include checking for an invalid option (and you should probably also make sure both FILE1 and FILE2 were specified). Fourth, when checking whether $outputfile is blank, you need double-quotes around it and then use a string test (-eq checks for numeric equality, and will give an error if you use it to compare anything other than numbers). Fifth, you should have double-quotes around the filenames in case they have any funny characters in them. Finally, the actual commands you're trying to execute (paste, tr, etc) don't make sense (so I pretty much left them alone). Here's my shot at a rewrite:

#!/bin/sh
outputfile=''
while getopts "o:" OPTION
do
    case $OPTION in
    o)
        outputfile="$OPTARG"
    ;;
    [?])
        echo "Usage: $0 [-o outfile] file1 file2" >&2
        exit 1
    ;;
    esac
done
shift $(($OPTIND-1))

if [ $# -ne 2 ]; then
    echo "Usage: $0 [-o outfile] file1 file2" >&2
    exit 1
fi
FILE1="$1"
FILE2="$2"

if [ -n "$outputfile" ]; then
    cat "$FILE1" | paste - | "$FILE1" - | tr "\t" "\n" | paste "$FILE1" "$FILE2" | tr '\t' '\n' > "$outputfile"
else
    cat "$FILE1" | paste - | "$FILE1" - | tr "\t" "\n"
    paste "$FILE1" "$FILE2" | tr '\t' '\n'
fi

Upvotes: 6

Related Questions