I have a script which can get tens of arguments/flags using Getopt::Long
.
Certain flags are not allowed to be mixed, such as: --linux --unix
are not allowed to be supplied together. I know I can check using an if
statement. Is there is a cleaner and nicer way to do that?
if
blocks can get ugly if I don't want to allow many combinations of flags.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments". $# is read-only. When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.
Command-line arguments are parameters that are passed to a script while executing them in the bash shell. They are also known as positional parameters in Linux. We use command-line arguments to denote the position in memory where the command and it's associated parameters are stored.
It does not seem that Getopt::Long has such a feature, and nothing sticks out after a quick search of CPAN. However, if you can use a hash to store your options, creating your own function doesn't seem too ugly:
use warnings;
use strict;
use Getopt::Long;
my %opts;
GetOptions(\%opts, qw(
linux
unix
help
)) or die;
mutex(qw(linux unix));
sub mutex {
my @args = @_;
my $cnt = 0;
for (@args) {
$cnt++ if exists $opts{$_};
die "Error: these options are mutually exclusive: @args" if $cnt > 1;
}
}
This also scales to more than 2 options:
mutex(qw(linux unix windoze));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With