Search code examples
batch-filesetprompt

In batch SET /P command "?" crashes with "was unexpected at this time"


It sounds I can't put "?" in prompt in batch (.bat) scripts:

set /p AREYOUSURE= Are you sure (Y/[N]) ?

It crashes with the message :

? was unexpected at this time.

However, it works well without the ""

Note: I'm running with Windows 7 64bits.


Solution

  • This isn't because of the question mark, it's because of the closing parenthesis. You are using this statement in a block, e.g.

    if foo (
      set /p AREYOUSURE= Are you sure (Y/[N]) ?
    )
    

    The closing parenthesis closes the block, which then lets the parser stumble over the first character after the block.

    You can escape the closing parenthesis:

    set /p AREYOUSURE= Are you sure (Y/[N]^) ?
    

    or just use quotes, which I'd always recommend anyway:

    set /p "AREYOUSURE=Are you sure (Y/[N])?"
    

    For questions like these I'd personally use choice, however:

    choice /m "Are you sure"
    

    You can't do a default choice when just pressing return that way, though.