bashshellubuntu-13.04

new to Bash - keep getting Illegal option error


I'm quite new to ubuntu and bash scripting and wanted to know why I might be getting this error when using GETOPTS.

here is the code I use to run it.

sh /home/ubuntu/Desktop/test.sh -f /home/u/Desktop/ -p 'TEST'

I think i'm calling the script correctly, and it should search for the term I enter as a search term using grap. but for some reason it doesn't. Any advice on what I can do as a general rule when working with grep would also be appreciated, thanks.

#!/bin/bash

valid=0
file_arg=""
display_help=""
column=""
pattern=""

while getopts f:d:s:m: opt
do
    case "$opt" in
        d)  display_help=$OPTARG
            ;;
        f)  file_arg=$OPTARG
            ;;
        c)  column=$OPTARG
            ;;
        p)  pattern=$OPTARG
            ;;
        *)  valid=1
            break
            ;;
    esac
done

if [ $valid -eq "0" ]
then
    if [ $pattern != "" ]
    then
        cat $file_arg | grep $pattern
    else
        cat $file
    fi
else
    echo -n "Usage: FILE -f <name> | COLUMN -> -c <name> | HELP -> -d | PATTERN -> -p <expression>"
fi

Solution

  • In getopts you not specify p option you only have f:d:s:m: options.

    I think you mean p instead m or vice versa.

    It should f:d:s:m:p: or f:d:s:p: