Operating System - Linux
1753842 Members
8948 Online
108806 Solutions
New Discussion юеВ

User input for command flags

 
SOLVED
Go to solution
Vic S. Kelan
Regular Advisor

User input for command flags

I am trying to set up a shell script that will prompt a user to enter a date and a second parameter.

For example if the command is:

-t '02/12/08' -q 'group=MY_GROUP'

What can I do to get the user to input the date he/she wants and keep it in the above format (MM/DD/YY) and also get prompted to enter the group name?

Any help will be appreciated very very much!

5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: User input for command flags

Hi Vic:

Since your example is the standard switch-plus-argument format, you should consider using 'getopts()' to parse the switches and arguments.

http://docs.hp.com/en/B3921-60631/getopts.1.html

You are going to have to examine and verify the argument for "correctness" thereafter. For example, a valid date in the format shown would have a one or two digit month in the range 1-12. Similarly, you will have to define what constitutes a valid argument for '-q'.

Using regular expressions with 'grep' or 'awk' will help in the date validation, although you could simply 'cut' the field into pieces and make appropriate verifications to do that.

Regards!

...JRF...
Vic S. Kelan
Regular Advisor

Re: User input for command flags

Thanks JRF, I am not very familiar with the getopts and could not figure out how to use it from the man, actually very rusty with scripts. Do you have an example that could lead me on my way and I take it from there?

Thanks!
David Bellamy
Respected Contributor
Solution

Re: User input for command flags

This is something that i put together in perl, hope this helps.

#!/usr/bin/perl
use strict;
use diagnostics;
use warnings;

my $group;
print "Please Enter Date in the format MM/DD/YY: ";
my $date=;
chomp($date);
while() {
if($date=~/[0-1][0-9]\/[0-3][0-9]\/\d\d/) {
print "Please Enter Group Name: ";
$group=;
exit(0);
}else{
print "Invalid Date\n";
print "Please Enter Date in the format MM/DD/YY: ";
$date=;
}
}
James R. Ferguson
Acclaimed Contributor

Re: User input for command flags

Hi (again) Vic:

This should get you started:

# cat .example
#!/usr/bin/sh
while getopts t:q: THINGS
do
case ${THINGS} in
t)
OPT_T=1
VAL_T=${OPTARG}
;;
q)
OPT_Q=1
VAL_Q=${OPTARG}
;;
?)
printf "Usage: %s: [-t date] [-q value]\n" $0
exit 2;;
esac
done
if [ ! -z "${OPT_T}" ] ; then
printf "Option -t with %s\n" ${VAL_T}
fi
if [ ! -z "${OPT_Q}" ] ; then
printf "Option -q with %s\n" ${VAL_Q}
fi
shift $(( $OPTIND -1 ))

if [ $# = 0 ]; then
print "No arguments remain"
else
printf "Arguments remaining: %s\n" "$@"
fi
exit 0

# ./example -q group=mine -t 02/12/2008 myfile
Option -t with 02/12/2008
Option -q with group=mine
Arguments remaining: myfile

Regards!

...JRF...
Vic S. Kelan
Regular Advisor

Re: User input for command flags

Thanks guys, this really helped!