#!/path/to/Rscript
library('getopt');
#get options, using the spec as defined by the enclosed list.
#we read the options from the default: commandArgs(TRUE).
opt = getopt(c(
'verbose', 'v', 2, "integer",
'help' , 'h', 0, "logical",
'count' , 'c', 1, "integer",
'mean' , 'm', 1, "double",
'sd' , 's', 1, "double"
));
#help was asked for.
if ( !is.null(opt$help) ) {
#get the script name (only works when invoked with Rscript).
self = commandArgs()[1];
#print a friendly message and exit with a non-zero error code
cat(paste("Usage: ",self,"[-[vh]] [-[-mean|m] <mean>] [-[-sd|s] <sd>] [-[-count|c] <count>]
",sep=""));
q(status=1);
}
#set some reasonable defaults for the options that are needed,
#but were not specified.
if ( is.null(opt$mean ) ) { opt$mean = 0 }
if ( is.null(opt$sd ) ) { opt$sd = 1 }
if ( is.null(opt$count ) ) { opt$count = 10 }
if ( is.null(opt$verbose ) ) { opt$verbose = FALSE }
#print some progress messages to stderr, if requested.
if ( opt$verbose ) { write("writing...",stderr()); }
#do some operation based on user input.
cat(paste(rnorm(opt$count,mean=opt$mean,sd=opt$sd),collapse=""));
cat("");
#signal success and exit.
#q(status=0);
### END ###
#regression tests follow. not part of the example.
spec = c(
'verbose', 'v', 2, "integer",
'help' , 'h', 0, "logical",
'dummy1' , 'd', 0, "logical",
'dummy2' , 'e', 2, "logical",
'count' , 'c', 1, "integer",
'mean' , 'm', 1, "double",
'sd' , 's', 1, "double",
'output' , 'O', 1, "character"
);
opt = getopt(spec, c('-c', '-1', '-m', '-1.2'));
opt = getopt(spec, c('-v', '-m', '3'));
opt = getopt(spec, c('-m', '3', '-v'));
opt = getopt(spec, c('-m', '3', '-v', '2', '-v'));
opt = getopt(spec, c('-O', '-', '-m', '3'));
opt = getopt(spec, c('-m', '3', '-O', '-'));
opt = getopt(spec, c('-de'));
opt = getopt(spec, c('-ed'));
opt = getopt(spec, c('-d'));
opt = getopt(spec, c('-e', '1'));
opt = getopt(spec, c('-de', '1'));
opt = getopt(spec, c('--verbose'));
opt = getopt(spec, c('--help'));
opt = getopt(spec, c('--verbose', '--help'));
opt = getopt(spec, c('--verbose', '--mean', '5'));
opt = getopt(spec, c('--mean=5'));
opt = getopt(spec, c('--verbose', '--mean=5'));
opt = getopt(spec, c('--verbose', '--mean=5', '--sd', '5'));
opt = getopt(spec, c('--mean=5', '--sd', '5', '--verbose'));
opt = getopt(spec, c('--mean=5', '--verbose', '--sd', '5'));
spec = c(
'date' , 'd', 1, "character",
'help' , 'h', 0, "logical",
'getdata' , 'g', 0, "logical",
'market' , 'm', 1, "character",
'threshold', 't', 1, "double"
);
opt = getopt(spec, c('--date','20080421','--market','YM','--getdata'));
opt = getopt(spec, c('--date','20080421','--getdata','--market','YM'));
opt = getopt(spec, c('--date','20080421','--getdata','--market','YM'),debug=TRUE);
print(getopt(spec, c('--date','20080421','--getdata','--market','YM'),usage=TRUE));Run the code above in your browser using DataLab