1

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

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot I am very new to bash programming. when I run this program and say ./test file1 file2 it prints the correct output but first says file1 not found and if I use ./test -o hello file1 file2 it says file1 not found still.
The ...| "$FILE1" - |... part tries to execute $FILE1 as a command, which'll give you a "command not found" error. That's part of the reason I said that section didn't make much sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.