The Linux Page

Quoting to run MS-DOS commands with system()

As I am working on wpkg, a tool to build and manage advanced packages, I encounter problems running MS-DOS scripts. I am not the strongest in that realm. I have been working with Unix scripts for a little over 15 years and MS-DOS scripts are so limiting...

Anyway, to run a batch file, you need to write a script in a file that ends with .bat and to make sure it gets run properly, you want to run it using the %COMSPEC% command using the /c flag.

If parameters to the command include spaces, you want to place those parameters between double quotes. Although some commands are capable of transforming multiple command line parameters in a single filename, but it is really not safe when running abitrary commands from another software.


%COMSPEC% /c run-this-command.bat "this is a path with spaces"

Now, what do you do if the batch command itself includes a space (or has a path with a space)? You also have to quote the command, but you must also have to quote the command and its parameters because the /c command option accepts one parameter if it starts with a quote.

Now the result looks funny since you have two double quotes at the beginning and two at the end.


%COMSPEC% /c ""run this command.bat" "this is a path with spaces""

As you can see, the parameter after the /c starts and ends with two double quotes. This is how you quote a command line or program that you want to run with COMSPEC when this one (or the path to this one) includes one or more spaces in its filename.