Getopts option -please help

Hello,

I am using below code in AIX env to interpret -n option given in argument while executing the script .I want to give another argument -t

#!/bin/sh
#set -x
while getopts ":n:" opt; do
    case "$opt" in
        n)
            host=$OPTARG
            shift 2
        ;;
        *)
            break
        ;;
    esac
done

echo "host = $host "

I want to run script like ./ser_reloc.sh -n dev-u1 -t pref

How do I recognize second argument -t in the script
Additionally,if I place -t before -n and use script like below:

./ser_reloc.sh  -t  perf -n dev-u1 

would I have to change code for this?

Best regards,
Vishal

Use

#!/bin/sh
#set -x
while getopts ":n:t:" opt; do
    case "$opt" in
        n)
            host=$OPTARG
        ;;
        t)
            targ=$OPTARG
        ;;
        *)
            break
        ;;
    esac
done

echo "host = $host targ = $targ"

Do not use shift , because getopts is already taking care of removing option-arguments.

$ ./script.sh -n abc -t def
host = abc targ = def
1 Like

I also want to send the user an error message if the user doesn't input the
-n and -t correctly

-n is node name so I would ping this and if ping is working then its fine else an error message needs to be displayed to user that please input a valid host name .Similarly I want the user to input -t as pref or avail .If that doesn't happen then it should error out saying user that please input a valid value

Best regards,
Vishal

After the while...done loop you could write

if ping -w 2 $host >/dev/null 2>&1
then
    echo Host OK
else
    echo Bad Host $host
fi

and

case "$targ" in
    pref|avail) echo targ OK;;
    *)    echo Bad argument to -t;;
esac
1 Like