Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding mix of certain arguments to script

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.

like image 411
snoofkin Avatar asked Apr 24 '12 13:04

snoofkin


People also ask

How do I pass multiple arguments to a shell script?

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 …

How do you take an argument in a script?

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.

How do you determine the number of arguments passed to the 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.

What is a command line script argument?

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.


1 Answers

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));
like image 155
toolic Avatar answered Oct 18 '22 04:10

toolic