Page 1 of 1

Cmd.exe bug with special characters

Posted: 07 Feb 2021 12:50
by xpdev
I have a batch file called

Code: Select all

`#'`#!^% ^%os%'&!&(.bat
with the following:

Code: Select all

@echo off
echo Test
echo %0
echo Test 2
If I escape the characters like this:

Code: Select all

set p=%
"`#'`#!^%p% ^%p%os%p%'&!&(.bat"
Then every command works.
But if I escape them like this:

Code: Select all

`#'`#!^^^%" "^^^%os^%'^&!^&^(.bat
Then only the first command works. The batch file exits after that. Why does this bug happen?

Re: Cmd.exe bug with special characters

Posted: 09 Feb 2021 08:31
by jfl
This is because %0 is the command string you typed, not the actual script name.
In the first case, it's quoted, so the special characters do not confuse the echo command.
In the second case, it's not quoted, and the special & and ( characters (which have lost their protecting ^ at this stage) do confuse it.

It would fail in both cases if you used %~0 instead of %0, thereby eliminating quotes in both cases.
Conversely, "%~0" would make it work in both cases.

Re: Cmd.exe bug with special characters

Posted: 10 Feb 2021 10:19
by jeb
Hi,

as JFL already said, the echo %0 is the problem.

If you want to see the content without problems, you could use the REM technique.

Code: Select all

@echo off
echo Test

echo on
REM # %0 #
@echo off

echo Test 2