Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I escape an arbitrary string for use as a command line argument in Windows?
    text
    copied!<p>I have a list of strings and I want to pass those strings as arguments in a single Windows command line call. For simple alphanumeric strings it suffices to just pass them verbatim:</p> <pre><code>&gt; script.pl foo bar baz yes no foo bar baz yes no </code></pre> <p>I understand that if an argument contains spaces or double-quotes, I need to backslash-escape the double-quotes and backslashes, and then double-quote the argument.</p> <pre><code>&gt; script.pl foo bar baz "\"yes\"\\\"no\"" foo bar baz "yes"\"no" </code></pre> <p>But when I try to pass an argument with literal percent signs, this happens:</p> <pre><code>&gt; script.pl %PATH% C:\Program Files\PHP\;C:\spaceless\perl\bin\;C:\Program Files\IBM\Java60\bin; (...etc.) </code></pre> <p>Double quoting doesn't work:</p> <pre><code>&gt; script.pl "%PATH%" C:\Program Files\PHP\;C:\spaceless\perl\bin\;C:\Program Files\IBM\Java60\bin; (...etc.) </code></pre> <p>Nor does backslash-escaping (notice how the backslashes are present in the output):</p> <pre><code>&gt; script.pl \%PATH\% \%PATH\% </code></pre> <p>Also, the rules are inconsistent for backslash-escaping backslashes:</p> <pre><code>&gt; script.pl "\\yes\\" \\yes\ &gt; script.pl "\yes\\" \yes\ &gt; script.pl "\yes\" \yes" </code></pre> <p>Also, doubtless there are special characters in the Windows command line shell, much like there are in all shells. <strong>What, then, is the general procedure for safely escaping arbitrary command line arguments for use at the Windows command line?</strong></p> <p>The ideal answer will describe a function <code>escape()</code> which can be used in situations like the following (a Perl example):</p> <pre><code>$cmd = join " ", map { escape($_); } @args; </code></pre> <p>Here are some more example strings which should be safely escaped by this function (I know some of these look Unix-like, that's deliberate):</p> <pre><code>yes no child.exe argument 1 Hello, world Hello"world \some\path with\spaces C:\Program Files\ she said, "you had me at hello" argument"2 \some\directory with\spaces\ " \ \\ \\\ \\\\ \\\\\ "\ "\T "\\T !1 !A "!\/'" "Jeff's!" $PATH %PATH% &amp; &lt;&gt;|&amp;^ ()%!^"&lt;&gt;&amp;| &gt;\\.\nul malicious argument"&amp;whoami *@$$A$@#?-_ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload