Hi

a similar topic already came up which was about how to quote shell parameters so they are safe to pass to the shell.
I have another problem, I get as input a string containing the shell command to execute with it's parameters. Now I want to re-quote that so it's not going to execute something unwanted.
e.g. this

ls -al "file 1" "file'2" ; cat /etc/passwd
is transformed into
ls '-al' 'file 1' 'file'\''2' ';' 'cat' '/etc/passwd'
and ls will complain about non found files ";" and "cat".
Here is the current code I have come up with.
#!/usr/bin/perl # used http://www.cs.hmc.edu/courses/2003/spring/cs60/fsm.pdf # to transform state machine into regexp $cmd=<>; $arg=""; chomp $cmd; $cmd.=" "; # regexp # ( |([^'"\\ ]+)|(\\.)|("(([^"\\])|(\\.))*")|('[^']*')) # only global matching # ( |(?:[^'"\\ ]+)|(?:\\.)|(?:"(?:(?:[^"\\])|(?:\\.))*")|(?:'[^']*')) # we need to do second subst to remove " and ' pairs and unescape \ so + need some flags # ( |(?:[^'"\\ ]+)|(\\.)|("(?:(?:[^"\\])|(\\.))*")|('[^']*')) while($cmd=~s/^( |(?:[^'"\\ ]+)|(\\.)|("(?:(?:[^"\\])|(\\.))*")|('[^'] +*'))(.*)$/$6/) { $c=$1; # the flags... $esc=$2; $dquote=$3; $dquoteEsc=$4; $squote=$5; print "c=$c arg=$arg cmd=$cmd esc=$esc dquote=$dquote dquoteEsc=$dqu +oteEsc squote=$squote\n"; if($c eq " ") { $arg=~s/'/'\\''/g; # shell escape the ' $res .= "'$arg' "; $arg=""; next; } if(($esc ne "")|($dquoteEsc ne "")) { $c=~s/\\//g } if($dquote ne "") { $c =~ s/^"(.*)"$/$1/} if($squote ne "") { $c =~ s/^'(.*)'$/$1/} $arg .= $c; } print "$res\n";

In reply to safe quoting for shell parameters by Gunstick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.