Escaping outputs in CMD

大兔子大兔子 提交于 2020-02-05 06:29:13

问题


If I run something that returns with a & or some other character that has special meaning, and I try to use it in a script, how would I escape it?

An example would be if I shared a local account with someone in the same computer, and I had a username that says John & Matt. Putting a batch file in the Desktop directory that had something like this:

@ECHO OFF
echo %~dp0

It would return something like this:

C:\Users\John
The system cannot find the path specified.

And the whole script from that point on breaks if I try to keep going. If anyone knows a way to make the whole path appear, I'd appreciate it.

EDIT: I didn't clarify this enough earlier. Sorry about that. Not really good at explaining, but if I try to use %~dp0 in a variable, and stack more things on top of that, something like

SETLOCAL
set loc=%~dp0
rename "%~dp0Dir\Dir1\Dir2\File.txt" "Something.txt"

It would probably confuse the rename command if I put another set of quotation marks when I'm declaring a variable to fix that issue.

The batch file that I was trying to create basically deletes a file where the batch file is located, replaces it with another file in a subfolder located inside the directory where the batch file is, and renames it to something else.


回答1:


If you want to reliably ECHO the value without enclosing quotes, then you can use either of the following strategies:

@echo off
:: Use a FOR loop
for %%F in ("%~dp0") do echo %%~F

:: Use delayed expansion.
:: Note that delayed expansion must be enabled after assignment of fullPath,
:: else any ! within path will be corrupted during the assignment.
set "fullPath=%~dp0"
setlocal enableDelayedExpansion
echo !fullPath!



回答2:


@ECHO OFF
echo %dp0

will return dp0 - I guess you mean %~dp0 ;-)

However, echo "%~dp0" will output C:\Users\John & Matt\...

By the way, it's \ and not /.

Windows: \

Unix/Linux: /

I'm not being pedantic, this sometimes causes serious problems (like here).



来源:https://stackoverflow.com/questions/42347115/escaping-outputs-in-cmd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!