Skip to content

Instantly share code, notes, and snippets.

@tommybutler
Created February 11, 2014 20:27
Show Gist options
  • Save tommybutler/8943404 to your computer and use it in GitHub Desktop.
Save tommybutler/8943404 to your computer and use it in GitHub Desktop.
parse a command invocation into the command and each of its arguments
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use Data::Dumper;
my $cmdstr = q{/usr/local/bin/ssh %s '/opt/something/bin/somebinary || echo "Could not execute somebinary"' -a -abc --verbose --name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo};
my ( $cmd, $argstr, @args );
{
$cmdstr =~ s/^(.*?)[[:space:]]+(.*)//;
$cmd = $1;
$argstr = $2;
}
my $i = 0; # failsafe
while ( $i++ < 20 && length $argstr )
{
if ( $argstr =~ /^"/ )
{
$argstr =~ s/^"(.*?[^\\])"//;
push @args, $1;
}
elsif ( $argstr =~ /^'/ )
{
$argstr =~ s/^'(.*?)'//;
push @args, $1;
}
elsif ( $argstr =~ /^[^[:space:]"']+["']+/ )
{
if ( $argstr =~ s/^([^[:space:]"]+".*?[^\\]")// )
{
push @args, $1;
}
else
{
$argstr =~ s/^([^[:space:]']+'.*?')//;
push @args, $1;
}
}
else
{
$argstr =~ s/^([^[:space:]]+)//;
push @args, $1;
}
$argstr =~ s/^[[:space:]]+//;
say qq(argstr => {{{$argstr}}});
}
say qq{command: $cmd};
say Dumper \@args;
__END__
output:
argstr => {{{'/opt/something/bin/somebinary || echo "Could not execute somebinary"' -a -abc --verbose --name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{-a -abc --verbose --name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{-abc --verbose --name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{--verbose --name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{--name="tommy butler" --color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{--color="blue" --quote="'to be'" /tmp /foo}}}
argstr => {{{--quote="'to be'" /tmp /foo}}}
argstr => {{{/tmp /foo}}}
argstr => {{{/foo}}}
argstr => {{{}}}
command: /usr/local/bin/ssh
$VAR1 = [
'%s',
'/opt/something/bin/somebinary || echo "Could not execute somebinary"',
'-a',
'-abc',
'--verbose',
'--name="tommy butler"',
'--color="blue"',
'--quote="\'to be\'"',
'/tmp',
'/foo'
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment