Search This Blog

Showing posts with label getopt. Show all posts
Showing posts with label getopt. Show all posts

Friday, September 18, 2015

Using commandline options in shell scripts

Sample code using getopt

while getopts :f:cuh OP
do
            case ${OP} in
                           f)         SERVERS=${OPTARG}
                                       ;;
                           c)        if [ "${SERVERS}" != "false" ]
                                      then
                                                check
                                       else
                                               usage
                                      fi
                                      ;;
                           u)       if [ "${SERVERS}" != "false" ]
                                     then
                                                cd ${BASE}
                                      fi
                                     ;;
                        *|h)      usage
                                     ;;
                     esac
done

Thursday, December 23, 2010

Perl script options

Using getopt in perl scripts.
Sample code
#!/usr/bin/perl
#-------------------------------------------------------------------------
#       Using getop
#-------------------------------------------------------------------------
use Getopt::Std;
getopt('cw');
my @op = `./x.sh -c $opt_c -w $opt_w`;
foreach (@op)
{
        #printf "-c %s\t-w %s\n", $opt_c,$opt_w;
        print $_;
}

Output
./x.pl -c 3 -w 55
in ./x.sh.sh : -c 3 -w 55
-c 3
-w 55

or

my %options=();
#Pre set default values 
my $critv=95;
my $warnv=85;
getopts("c:w:", \%options);
$critv = $options{c} if defined $options{c};
$warnv = $options{w} if defined $options{w};

This method won't report an error if an option is emitted.