Search code examples
variablesbatch-filecommandsetnul

Using >nul in a variable


Does anyone know how to stop >nul being ignored when set in a variable, or is this not possible? I have a feeling that it's one of those things that will only work once all variables have been expanded or something, but it can't hurt to ask.

Example:

@echo off

:: Won't work
SET pause_5=ping localhost /n 6 >nul
%pause_5%

:: Will work
SET pause_5=ping localhost /n 6
%pause_5% >nul

exit

Solution

  • Put quotes around the argument:

    set "pause_5=ping localhost /n 6 >nul"
    

    Another option is to escape characters that will be interpreted by the shell:

    set pause_5=ping localhost /n 6 ^>nul
    

    But usually the quotes approach is a lot easier.

    The way you wrote is essentially said »set pause_5 to ping localhost /n 6 and ignore the output of the set command.«.