Ecranning quotes in Windows CMD - cmd

Can I do something like ecranning quotes in variable? For example,
if "%1"=="/?" goto :help
Will return error if argument is "

Try "%~1". The tilde modifier will strip quotes from %1, if present.
Unfortunately there is no general safe way to process strings with special chars (quotes, parentheses, caret) in batch files. There are always some cases that blow up whatever you write.

Related

How to escape % inside double quotes in cmd?

In cmd I'm trying to do something like
program.exe -command "otherprogram.exe %thing% %path%"
The issue I'm having is that I can't figure out how to escape the % characters when they're inside double quotes, but I need the double quotes because of the spaces in this argument. Basically I don't want cmd to do variable expansion before passing the argument value to program.exe.
Just to be clear, this is directly in cmd, not in a batch script.
A simple semi solution is:
program.exe -command ^"otherprogram.exe %th^ing% %pa^t^h%^"
The positions of the carets inside the variable name are random.
This still could fail, but only for the rare case, if variables exists named thi^ng or pa^t^h
It seems strange, but don't escape the percent signs. Put a caret (the escape sign for every other special char) anywhere within the variable name: echo %^username% or `echo %use^rname%.
The first parsing removes the ^ (because there is (hopefully) no variable with that name). On command line (other than in a batch file), an empty variable doesn't show nothing, but the variable name including the surrounding %'s.
Any further level of parsing then receives the "normal" variable and expands it. Prove:
echo %usern^ame%
call echo %usern^ame%
Not your question, but for the sake of completeness: in a batch script, simply escape the % with another %:
echo %%username%%
call echo %%username%%

Call .exe from batch file with variable path containing spaces

I want to launch a windows executable from a batch file where the path to the executable is stored in a variable.
#echo off
set qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin
set execpath=%qtpath%\windeployqt.exe
echo %execpath%
%execpath% --someparams
Unfortunately executing my script throws an error:
'C:\Program' is not recognized as an internal or external command, operable program or batch file.
Looks like somehow the string gets terminated at the space in Program Files.
You should change your code to this:
#echo off
set "qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin"
set "execpath=%qtpath%\windeployqt.exe"
echo "%execpath%"
"%execpath%" --someparams
The SPACE, like also TAB, ,, ;, =, VTAB (vertical tabulator, ASCII 0x0B), FF (form-feed, ASCII 0x0C) and NBSP (non-break space, ASCII 0xFF) constitute token separators in the command prompt cmd. To escape tokenisation enclose your path in between "". This avoids also trouble with special characters like ^, ( and ), &, <, > and |.
The quotation marks in the set command lines again avoid trouble with special characters; they do not become part of the variable value because they enclose the entire assignment expression. Note that this syntax requires the command extensions to be enabled, but this is the default anyway.
I recommend not to include the quotation marks into variable values (set VAR="some value"), because then you could run into problems particularly when concatenating strings due to unwanted (double-)quotation (for instance, echo "C:\%VAR%\file.txt" returns "C:\"some value"\file.txt").
You are perfectly right. If the path to the file you want to execute contains spaces, you have to surround it with quotation marks:
#echo off
set qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin
set execpath="%qtpath%\windeployqt.exe"
echo %execpath%
%execpath% --someparams
This should work.
It will also work when you surround %execpath% with quotation marks:
"%execpath%" --someparams

How to pass escaped double quote to batch file

I know there were similar questions, but there is one thing I can't find in the answers. I'm trying to pass the following string to batch file:
hello " world
This is a single argument. Here is my batch file:
#echo off
#echo %1
Now if I run it from command line, I'm getting the following results:
>C:\file.bat "hello "" world"
"hello "" world"
>C:\file.bat "hello \" world"
"hello \"
>C:\file.bat "hello """ world"
"hello """
In all cases I'm getting the wrong result, how do I escape a double quote and pass it correctly? Or should I do any additional conversion steps in the batch file itself?
It is impossible to pass a string literal value of hello " world as a batch parameter for two reasons:
Space cannot be escaped with regard to parameter tokenization. Parameters are always delimited by unquoted token delimiters, even if they are preceded by the ^ escape character. The token parameter token delimiters are {space}, {tab}, ,, ; =, and {0xFF}. The only way to include a token delimiter as part of a parameter is to make sure the delimiter is quoted.
It is impossible to escape a quote within a quoted string. Quotes are a state machine: The first encountered quote turns on quote semantics, and the subsequent one turns it off. The next quote turns it back on again, etc. If quoting is off, then a quote literal can be escaped as ^" to keep quoting off. But once quoting has begun, then there is no way to escape a closing
quote: The next quote always turns quoting off.
So no matter how you add quotes and/or escaped quotes, there will always be an unquoted space, thus the string will be treated as two parameters.
You could adopt the strategy recommended by Hapax - Quote the entire string, and double any quote literals within the string: "Hello "" world".
However I would make a slight change and use %~1 instead of %1 so as to remove the outer quotes. Then the doubled quotes should be converted back to a single quote:
#echo off
set "arg1=%~1"
set "arg1=%arg1:""="%"
echo %arg1%
But there are other potential issues with passing string literals as batch parameters. The most insidious is caret doubling. It is impossible to pass a quoted caret as a parameter if the caller uses CALL. I won't get into the mechanism behind the problem. See https://stackoverflow.com/a/4095133/1012053 if you want more information. But the following illustrates the problem:
test.bat
#echo %1
-- Sample cmd session --
D:\test>test "^"
"^"
D:\test>call test "^"
"^^"
Because of the many complications with passing string literals as batch parameters, the most effective strategy used in advanced batch scripting is to store the value in an environment variable, and then pass the variable name as the parameter. The batch script can then use delayed expansion to get the correct value:
test2.bat
#echo off
setlocal enableDelayedExpansion
set "arg1=!%1!"
echo !arg1!
-- Sample cmd session --
D:\test>set "myVar=Hello world! ^&|<>" How are you doing? !^^^&^|^<^>^"
D:\test>set myVar
myVar=Hello world! ^&|<>" How are you doing? !^&|<>
D:\test>test2 myVar
Hello world! ^&|<>" How are you doing? !^&|<>
D:\test>call test2 myVar
Hello world! ^&|<>" How are you doing? !^&|<>
The way to keep quotes is to pass them doubled. However, this passes both of them.
You can then process the input and remove the doubles.
Executing using file.bat "hello "" world", we use:
#echo off
set param=%1
set param=%param:""="%
echo %param%
(result: "hello " world")
A shorter version:
#echo off
set param=%1
echo %param:""="%

Batch path variable with space - how to escape the double quotes?

I'm setting a variable with this directory
C:\My dir\Sub dir\Folder with a lot of spaces\file.html
like this:
SET location="C:\My dir\Sub dir\Folder with a lot of spaces\file.html"
The problem is, when I echo %location% it comes with both double quotes. I've tried to remove using this:
set location=%location:"=\"%
But it does not work. I've searched a lot and I can't find an easy and simple solution. I'm using Windows 8.
An easy and simple solution is to store the path without the quotes, like this:
SET "location=C:\My dir\Sub dir\Folder with a lot of spaces\file.html"
This way the value will be stored with no quotes and the SET statement will still be protected from the effect of certain special characters. You will then either enclose %location% in quotes or omit the quotes as required. For instance, if you are using the value as an argument of some command, you will likely need to put the quotes around it:
somecommand "%location%" …
…
And if you just need to output the path, the quotes may be unnecessary – and it's easy to leave them out:
ECHO Location: %location%
…
Note that if the path has characters with special meaning, like &, ECHOing the path without the quotes would cause such characters to be interpreted in % evaluation. To avoid that, you could temporarily enable and use delayed expansion:
SETLOCAL EnableDelayedExpansion
ECHO Location: !location!
ENDLOCAL
…
Use set "location=C:\My dir\Sub dir\Folder with a lot of spaces\file.html" to keep the spaces but leave out the double quotes.
Don't use quotes in Set.
Later when you use that variable you include quotes around it eg
type "%location%"
Also this removes quotes
set location=%location:"=%
Yours I think replaces quotes with a backslash and a quote, not very useful.
Why even put it into a variable?

Escape double quotes in parameter

In Unix I could run myscript '"test"' and I would get "test".
In Windows cmd I get 'test'.
How can I pass double-quotes as a parameter? I would like to know how to do this manually from a cmd window so I don't have to write a program to test my program.
Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.
Here's a set of basic rules:
When not wrapped in double-quoted groups, spaces separate parameters:program param1 param2 param 3 will pass four parameters to program.exe: param1, param2, param, and 3.
A double-quoted group ignores spaces as value separators when passing parameters to programs:program one two "three and more" will pass three parameters to program.exe: one, two, and three and more.
Now to explain some of the confusion:
Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:hello"to the entire"world acts as one parameter: helloto the entireworld.
Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:"Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"
Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:
" open double-quote group
T inside ""s
i inside ""s
m inside ""s
inside ""s - space doesn't separate
s inside ""s
a inside ""s
y inside ""s
s inside ""s
, inside ""s
inside ""s - space doesn't separate
" close double-quoted group
" quote directly follows closer - acts as plain unwrapped text: "
H outside ""s - gets joined to previous adjacent group
i outside ""s - ...
! outside ""s - ...
" open double-quote group
" close double-quote group
" quote directly follows closer - acts as plain unwrapped text: "
Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says, is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.
As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.
From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:
"Tim said to him, """What's been happening lately?""""
will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.
Here are a few examples to close it off:
program a b REM sends (a) and (b)
program """a""" REM sends ("a")
program """a b""" REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d"" REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes"" REM sends (hello to "quotes")
program """"hello world"" REM sends ("hello world")
program """hello" world"" REM sends ("hello world")
program """hello "world"" REM sends ("hello) and (world")
program "hello ""world""" REM sends (hello "world")
program "hello """world"" REM sends (hello "world")
Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.
I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).
I cannot quickly reproduce the symptoms: if I try myscript '"test"' with a batch file myscript.bat containing just #echo.%1 or even #echo.%~1, I get all quotes: '"test"'
Perhaps you can try the escape character ^ like this: myscript '^"test^"'?
Try this:
myscript """test"""
"" escape to a single " in the parameter.
The 2nd document quoted by Peter Mortensen in his comment on the answer of Codesmith made things much clearer for me. That document was written by windowsinspired.com. The link repeated: A Better Way To Understand Quoting and Escaping of Windows Command Line Arguments.
Some further trial and error leads to the following guideline:
Escape every double quote " with a caret ^. If you want other characters with special meaning to the Windows command shell (e.g., <, >, |, &) to be interpreted as regular characters instead, then escape them with a caret, too.
If you want your program foo to receive the command line text "a\"b c" > d and redirect its output to file out.txt, then start your program as follows from the Windows command shell:
foo ^"a\^"b c^" ^> d > out.txt
If foo interprets \" as a literal double quote and expects unescaped double quotes to delimit arguments that include whitespace, then foo interprets the command as specifying one argument a"b c, one argument >, and one argument d.
If instead foo interprets a doubled double quote "" as a literal double quote, then start your program as
foo ^"a^"^"b c^" ^> d > out.txt
The key insight from the quoted document is that, to the Windows command shell, an unescaped double quote triggers switching between two possible states.
Some further trial and error implies that in the initial state, redirection (to a file or pipe) is recognized and a caret ^ escapes a double quote and the caret is removed from the input. In the other state, redirection is not recognized and a caret does not escape a double quote and isn't removed. Let's refer to these states as 'outside' and 'inside', respectively.
If you want to redirect the output of your command, then the command shell must be in the outside state when it reaches the redirection, so there must be an even number of unescaped (by caret) double quotes preceding the redirection. foo "a\"b " > out.txt won't work -- the command shell passes the entire "a\"b " > out.txt to foo as its combined command line arguments, instead of passing only "a\"b " and redirecting the output to out.txt.
foo "a\^"b " > out.txt won't work, either, because the caret ^ is encountered in the inside state where it is an ordinary character and not an escape character, so "a\^"b " > out.txt gets passed to foo.
The only way that (hopefully) always works is to keep the command shell always in the outside state, because then redirection works.
If you don't need redirection (or other characters with special meaning to the command shell), then you can do without the carets. If foo interprets \" as a literal double quote, then you can call it as
foo "a\"b c"
Then foo receives "a\"b c" as its combined arguments text and can interpret it as a single argument equal to a"b c.
Now -- finally -- to the original question. myscript '"test"' called from the Windows command shell passes '"test"' to myscript. Apparently myscript interprets the single and double quotes as argument delimiters and removes them. You need to figure out what myscript accepts as a literal double quote and then specify that in your command, using ^ to escape any characters that have special meaning to the Windows command shell. Given that myscript is also available on Unix, perhaps \" does the trick. Try
myscript \^"test\^"
or, if you don't need redirection,
myscript \"test\"
I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.
>powershell.exe "echo la`"" >> test
>type test
la"
Below are outputs I got for other characters to escape a double quote:
la\
la^
la
la~
Using another quote to escape a quote resulted in no quotes.
As you can see, the characters themselves got typed, but didn't escape the double quotes.
Maybe you came here, because you wonder how to escape quotes that you need in the command that you pass to /c on cmd.exe? Well you don't:
CMD /c "MKDIR "foo bar""
will execute
MKDIR "foo bar"
which is really a behavior that I did not expect in the first glance.

Resources