Script doesn't print error.

Hi Gurus,

I have below sample script. I expect it print error when running script without input parameter. but the it doesn't.

would you please help me about this issue.

thanks in advance.

/script$cat test.ksh
#!/bin/ksh
while getopts :f: arg
do
        case $arg in
                f) echo file is : $OPTARG
                        echo $OPTARG;;
                \?) echo "error";;
        esac
done
/script$./test.ksh -f abc
file is : abc
abc
/script$./test.ksh
/script$

If you run the script without options, then it will not enter the while loop.

1 Like

Hello Ken6503,

Could you please try following script as follows, hope it may help you.

#!/bin/ksh
while getopts ":f:" arg
do
        case $arg in
                f) echo file is : $OPTARG
                        echo $OPTARG;;
                \?) echo "error";;
                :) echo "Option -$OPTARG requires an argument."
                exit 1
        esac
done

if [[ $OPTIND == 1 ]]
then
        echo "No options were passed"
fi
:) echo "Option -$OPTARG requires an argument."
                exit 1

Above code will check if a option let's say -f is given while running script but no option was passed it will catch it.

Now come on to the OPTIND , if we read the man page then we will get to know that OPTIND

So I am checking here if it's value is 1 then it means no argument was provided while running script.

Script run without argument:

./test_try.ksh
No options were passed

Script run with option and argument:

./test_try.ksh -f chumma
file is : chumma

chumma

Script run with option without argument:

./test_try.ksh -f
Option -f requires an argument.

Hope this helps.

Thanks,
R. Singh

1 Like

Maybe something like this comes closer to what you're trying to do:

#!/bin/ksh
IAm=${0##*/}
file=
while getopts :f: arg
do
        case $arg in
	(f)	file="$OPTARG"
		printf 'Found -f option; setting file="%s"\n' "$file";;
	(\?)	printf 'Usage: %s -f file operand...\n' "$IAm" >&2
		exit 1;;
        esac
done
shift $((OPTIND - 1))
if [ "$file" = "" ]
then	printf '%s: No "-f file" option found.\n' "$IAm" >&2
	exit 2
else	printf 'Last "-f file" option set file to "%s"\n' "$file"
fi
printf 'Operands remaining after option parsing:\n'
printf '\t"%s"\n' "$@"

Note, however, that it is more common to use an operand (rather than an option) to specify a mandatory utility argument.

1 Like

Thanks everyone. you guys are great people.