Let's say I have the following in my AutoRun script:
@doskey cd = @( ^
for /f usebackq^^ delims^^=^^ eol^^= %%a in (^
'$* ' ^
) do @( ^
if "%%~a"==" " ( ^
if /i not "%%CD%%"=="%%USERPROFILE%%" ( ^
chdir /d "%%USERPROFILE%%" ^&^& ^
set "OLDPWD=%%CD%%" ^
) ^
) else if "%%~a"=="- " ( ^
if /i not "%%CD%%"=="%%OLDPWD%%" ( ^
chdir /d "%%OLDPWD%%" ^&^& ^
set "OLDPWD=%%CD%%" ^
) ^
) else ( ^
if /i not "%%CD%%"=="%%~a" ( ^
chdir /d "%%~a" ^&^& ^
set "OLDPWD=%%CD%%" ^
) ^
) ^
) ^
)
This is supposed to emulate the behaviour of POSIX cd in cmd.exe, and for the most part it works great:
C:\Users\user>cd C:\
C:\>cd
C:\Users\user>cd -
C:\>
However, all it takes is an incomplete pair of double quotes to make that house of cards fall:
C:\>cd "
2> was unexpected at this time.
Is there a way of sanitizing macro input inline so that it can handle misplaced quotes properly?
I've tried/thought of the following:
- creative use of
for /fwith single quotes - what you can see in the provided example: it doesn't break on a list of arguments during string comparison, but"is all it takes - turning the whole thing into a compound macro (i.e.
for /l (1, 1, 2)...combined withset args=,at the end) - nope, can't enable delayed expansion from command line context - ignore
$*and just use$1,$2etc. and hope for the best - doesn't solve the problem as DOSKEY doesn't care about double quotes when delimiting arguments and not applicable tochdiranyway when command extensions are enabled, as it does not treat spaces (or anything) as delimiters
One simple way is to use the definition batch file for some code, too.
The macro uses
set args=at the end and call then a batch file for the main code.With this technique the code is also much more readable.
Doskey only:
But if you insist to solve it only with a doskey macro, you could use disappearing carets.
Line2 do the trick:
FOR %%^^^^ in ("") dodefines an empty%%^FOR meta variable.This is used in
for /f "delims=" %%a in (^^""$*%%~^^"^")The
%%~^^escapes the next quote, but only if$*contains unbalanced quotes, and after the expansion the%%~^^disappears.The quote escaping solves the problem of unbalanced quotes in
$*, because in the case of none or balanced quotes in$*it expands to a balanced quote string, but this works even for unbalanced quotes in$*Batch file only version:
The great advantage of using a batch file, it can be used in batch files, too, but doskey macros can't.
That's because doskey macros has to be typed in via keyboard, they can't be activated in any other way.
But it can't be named
cd.batbecausecd.batwill only be called when the file is in the current directory, else the built incdwill be usedcdX.bat (the file should be in the path)