Rahul's Website

Tech, coding, security and other random stuff...

Command line arguments on Windows

Aug 032017

The following command shows how command line arguments basically work on Windows:

executable.exe arg1 "this is arg2" \"arg3 arg\"

These are the basics:

  1. Arguments are separated by spaces
  2. Strings inside double quotes are treated as a single argument
  3. To include a literal double quote, escape it using a backslash

Seems easy enough, right? Well, this will cover you for most cases, except...

Try the following out:

Command Arguments passed
executable.exe \\
executable.exe \"
executable.exe \\"
executable.exe \\\"

The last two cases don't make a lot of sense... So what's going on here? 

Turns out that backslashes can be used to escape backslashes themselves, but only when they are followed by double quotes... Confusing? Let me explain.

I've created a simple executable which tells me the command line arguments using code from here. Now let us try the second-to-last case again:

>executable.exe \\"
There are 2 arguments:
0 executable.exe
1 \

And now let us try the same thing with some extra text at the end:

>executable.exe \\" hi hi" lol
There are 3 arguments:
0 executable.exe
1 \ hi hi
2 lol

What do we see? The first backslash is escaping the second backslash, which is why the second backslash isn't escaping the double quotes, which is why the text between the quotes is getting treated as a single argument!

This also explains the last case. The third backslash is escaping the double quotes!

There are no published comments.

New comment