UFO ET IT

Windows 배치 스크립트에서 따옴표 처리

ufoet 2021. 1. 5. 08:27
반응형

Windows 배치 스크립트에서 따옴표 처리


Windows 배치 파일에서 다음을 수행하는 경우 :

set myvar="c:\my music & videos"

변수 myvar는 따옴표가 포함 된 상태로 저장됩니다. 솔직히 저는 그게 아주 멍청하다고 생각합니다. 따옴표는 문자열이 시작되고 끝나는 위치를 알려주기위한 것이며 값 자체의 일부로 저장되지 않습니다.
이런 일이 발생하지 않도록하려면 어떻게해야합니까?

감사.


set "myvar=c:\my music & videos"

myvar 전에 따옴표가 시작됩니다. 실제로 그렇게 간단합니다. 참고 : myvar는 &가 명령 구분 기호로 읽히기 때문에 따옴표로 묶지 않으면 나중에 에코 될 수 없지만 여전히 경로로 작동합니다.

http://ss64.com/nt/set.html 의 "변수 이름에는 공백이 포함될 수 있음"


이것이 올바른 방법입니다.

set "myvar=c:\my music & videos"

따옴표는 변수 값에 포함되지 않습니다.


변수를 사용하려는 방법에 따라 다릅니다. 따옴표없이 변수 값만 사용하려면 지연된 확장 및 문자열 대체 또는 다음 for명령을 사용할 수 있습니다 .

@echo OFF
SETLOCAL enabledelayedexpansion

set myvar="C:\my music & videos"

andynormancx가 말했듯이 문자열에 &. 또는으로 탈출 할 수 ^있지만 따옴표가 조금 더 깔끔하다고 생각합니다.

문자열 대체와 함께 지연 확장을 사용하는 경우 따옴표없이 변수 값을 얻습니다.

@echo !myvar:"=!
>>> C:\my music & videos

다음 for명령을 사용할 수도 있습니다 .

for /f "tokens=* delims=" %%P in (%myvar%) do (
    @echo %%P
)
>>> C:\my music & videos

그러나 명령에서 변수를 사용하려면 따옴표로 묶인 값을 사용하거나 변수 값을 따옴표로 묶어야합니다.

  1. 문자열 대체 및 지연 확장을 사용하여 따옴표없이 변수 값을 사용하지만 명령에서 변수를 사용합니다.

    @echo OFF
    SETLOCAL enabledelayedexpansion
    
    set myvar="C:\my music & videos"
    md %myvar%
    @echo !myvar:"=! created.
    
  2. for명령을 사용하여 따옴표없이 변수 값을 사용하지만 명령에서 사용할 때는 변수를 따옴표로 묶어야합니다.

    @echo OFF
    set myvar="C:\my music & videos"
    
    for /f "tokens=* delims=" %%P in (%myvar%) do (
        md "%%P"
        @echo %%P created.
    )
    

간단히 말해서 &배치 파일에 포함 된 공백 및 / 또는을 포함하는 경로 또는 파일 이름을 사용하는 깨끗한 방법은 없습니다 .


jscript를 사용하십시오.

몇 달 전 (즉, 약 8 년 전) 저는 대규모 C ++ / VB6 프로젝트에서 작업 중이었고 빌드의 일부를 수행하기위한 다양한 배치 스크립트가있었습니다.

그런 다음 누군가 Joel Test 에서 나를 가리 켰고 , 특히 포인트 2에 매혹되어 모든 작은 빌드 스크립트를 하나의 단일 빌드 스크립트로 가져 오기 시작했습니다. . .

그리고 그것은 내 마음을 거의 아프게 만들었고 모든 작은 스크립트가 약간 다른 설정으로 서로 다른 기계에서 함께 작동하게 되었기 때문에 끔찍했습니다. 특히 변수와 매개 변수 전달을 설정하는 것이 끔찍했습니다. 그것은 정말 부서지기 쉬웠고, 아주 사소한 것이 그것을 깨뜨리고 다시 시작하기 위해 30 분의 조정이 필요했습니다.

결국-나는 완고 할 수 있습니다- 나는 모든 것을 빠뜨 렸고 약 하루 만에 모든 것을 JavaScript로 다시 작성하고 CScript로 명령 프롬프트에서 실행했습니다.

나는 뒤돌아 보지 않았다. 요즘에는 MSBuild와 Cruise Control이지만 배치 스크립트와 약간 관련된 작업을 수행해야하는 경우 jscript를 사용합니다.


Windows 명령 인터프리터를 사용하면 전체 set 명령에 따옴표를 사용할 수 있습니다 (NT 4.0에서 Windows 2012 R2까지의 모든 Windows NT 버전에서 유효).

스크립트는 다음과 같이 작성해야합니다.

@echo OFF

set "myvar=C:\my music & videos"

그런 다음 필요에 따라 변수를 따옴표로 묶을 수 있습니다.

CMD 프롬프트로 작업하는 것은 때때로 난해 해 보일 수 있지만 명령 인터프리터는 실제로 내부 논리에 따라 매우 견고하게 작동하므로 상황을 다시 생각하면됩니다.

사실, set 명령은 따옴표를 전혀 사용하지 않아도되지만, 변수 할당을 수행하는 방식과 따옴표를 사용하지 않는 방법 모두 변수 주변에 추가 공백을 만들 수 있습니다. 스크립트를 디버깅 할 때주의하십시오.

예를 들어 아래 두 가지 모두 기술적으로 유효하지만 후행 공백이있을 수 있으므로 좋은 방법이 아닙니다.

set myvar=some text   
set myvar="some text" 

e.g. Both of the below are good methods for setting variables in Windows Command interpreter, however the double quote method is superior:

set "myvar=Some text"
(set myvar=Some value)

Both of these leave nothing to interpretation the variable will have exactly the data you are looking for.

strong text However, for your purposes, only the quoted method will work validly because you are using a reserved character

Thus, you would use:

set myvar="c:\my music & videos"

However, even though the variable IS correctly set to this string, when you ECHO the sting the command interpreter will interpret the ampersand as the keyword to indicate another statement follows.

SO if you want to echo the string from the variable the CMD interpreter still needs to be told it's a text string, or if you do not want the quotes to show you have to do one of the following:

echo the variable WITH Quotes:

Echo."%myvar%"

echo the variable WITHOUT Quotes:

Echo.%myvar:&=^&%
<nul SET /P="%myvar%"

In the above two scenarios you can echo the string with no quotes just fine. Example output below:

C:\Admin>    Echo.%myvar:&=^&%
C:\my music & videos

C:\Admin>    <nul SET /P="%myvar%"
C:\my music & videos
C:\Admin>

Try using the escape character '^', e.g.

set myvar=c:\my music ^& videos

You'll have you be careful when you expand myvar because the shell might not treat the & as a literal. If the above doesn't work, try inserting a caret into the string too:

set myvar=c:\my music ^^^& videos

You must have the quotes if the text you are setting includes certain characters, including &. If your text didn't include & then you wouldn't need the quotes.

For example if the text was just "c:\my music" then you could do:

set myvar = c:\my music

But because your text has a & you need the quotes.

Edit:

Or as Dave says in his answer you can escape the problem characters with ^^^, but beware of that approach as & isn't the only character you need to escape. In practice it is far easier to stick with the quotes rather than escaping all the problem characters.

ReferenceURL : https://stackoverflow.com/questions/535975/dealing-with-quotes-in-windows-batch-scripts

반응형