To tilde or not to tilde

batch filecmd.exe

When writing batch FOR loops I've picked up a habit of using tildes in the variable placeholder names in the command portion of the script and enclose that with double quotes.

Example Syntax

FOR %%A IN ("*.*") DO ECHO "%%~A"

enter image description here

Reason

I usually write scripts like this as a standard whether or not they are truly needed without thought. I like how it strips the double quotes from the set portion of the loop and then adds them back explicitly in the command parameter portion of the loop.

Question

  • Could there be a scenario where using the tilde could actually be harmful when used with a FOR loop via batch script or command line?

  • What are some reasons from others experience or perhaps officially documented somewhere why you would or would not want to use tildes for this reason with FOR loops via cmd or batch?

Best Answer

  • In your exact use case it doesn't make a difference but also doesn't harm :

    • as file names iterated by a wildcard are always returned unquoted.

    When iterating some double quoted strings (especially cmd line args %*)
    I'd always use them:

    @Echo off
    For %%A IN (
        "this is a sentence"
        two words
        "some words"
    ) Do (
        Echo with tilde: "%%~A"
        Echo w/o  tilde: "%%A"
        Echo:
    )
    

    > SU1397704.cmd
    with tilde: "this is a sentence"
    w/o  tilde: ""this is a sentence""
    
    with tilde: "two"
    w/o  tilde: "two"
    
    with tilde: "words"
    w/o  tilde: "words"
    
    with tilde: "some words"
    w/o  tilde: ""some words""