Using getopts. Need help

Hi all...

I have been looking on here for the past few days for an answer and Im gonna have to break down and ask.

I just learned about the getopts command last week so have been trying to utilize it in my scripts.

Below, I am trying to set up a case structure for options using getopts. The options I wanna use are -m, -t and -f. Ive gotten the -m and -t to work but if you look at my code the -f is not working when I test it. It seems like when I enter something on the command line like " mon -f dog"
where mon is my program name and dog is the file I wanna test for existence, the -f is actually passed as the argument. Any ideas?

mailopt=FALSE
interval=5
while getopts mft: option
do
case "$option"
in
m) mailopt=TRUE;;
t) interval=$OPTARG;;
f) if [ -f "$1" ]
then
echo "ok $1"
else
echo "no $1"
fi
exit 1;;
\?) echo "Usage: mon [-m] [-t n] [-f] user"
    echo "      -m means to be informed by mail"
    echo "      -t means check every n secs"
    echo "  -f means check for existence fo a file"
    exit 1;;
esac
done
if [ "$OPTIND" -gt "$#" ]
then
echo "Missing user name!"
exit 2
fi
shiftcount=$((OPTIND - 1))
shift $shiftcount
user=$1
until who | grep "^$user " > /dev/null
do
sleep $interval
done
term=$(who | grep $user | cut -d' ' -f3)
if [ "$mailopt" = FALSE ]
then
echo "$user has logged on $user has logged on to terminal $term"
else
runner=$(who am i | cut -c1-7)
echo "$user has logged on to terminal $term" | mail $runner
fi

---------- Post updated at 07:50 PM ---------- Previous update was at 07:40 PM ----------

Just realized if I switch the $1 in my if statement in the case to a $2 it actually works. So the if is reading my -f as an argument, not a variable. How can I fix it?

As -f takes an argument eg [-f file] you need a colon after it in the getopt argument:

while getopts mf:t: option

Then use $OPTARG to refer to the file (similar to what you did for -n):

f) if [ -f "$OPTARG" ]
   then
      echo "ok $OPTARG"
   else
      echo "no $OPTARG"
   fi
   exit 1;;
1 Like