17

Is there a way to present a default value in a set /p statement in a Windows batch script?

For example, something like this:

set /p MyVar=My Default Value
echo $MyVar$

If the user presses Enter without typing anything else, then `MyVar gets that default value.

Thanks.

2
  • This question has been answered several times before, like this, or this, or this, ...
    – Aacini
    Commented Feb 7, 2018 at 14:47
  • @Aacini Yeah might be... Interestingly I literally always find those duplicates in top positions of any search result. :) But thanks to your 1st link I found what I was really looking for, i.e. not just setting a default value but also preseting that default value to the user.
    – Andreas
    Commented Mar 15, 2022 at 6:10

3 Answers 3

27

This:

SET /P "MyVar=" || SET "MyVar=My Default Value"

(Read more).


You could also use this:

SET /P "MyVar="
IF NOT DEFINED MyVar SET "MyVar=My Default Value"
4
  • 7
    You could also preset the value because set won't overwrite it if the user presses enter without typing, e.g. set "MyVar=Default Value" & set /p "MyVar=Enter value: ".
    – Eryk Sun
    Commented Feb 7, 2018 at 3:12
  • @eryksun If the user presses enter without typing SET "MyVar=My Default Value" is processed (tested on Windows 10). Commented Feb 7, 2018 at 3:16
  • @eryksun It's late... fixed it, thanks. How does it come it's more reliable, tho? Commented Feb 7, 2018 at 3:22
  • It's a potential parsing problem with mismatched quoting if the user enters a string with double quotes.
    – Eryk Sun
    Commented Feb 7, 2018 at 3:26
8

Here is one method.

It will set %1 as myvar if defined, then skip the prompt and echo myvar else it will store Default Value as the default, but if someone types in another value, it will overwrite the default. Not you can also use %2 %3 etc.

@echo off
set "myvar=%1"
if "%myvar%"=="" set /p "myvar=Enter Value: " || set "myvar=Default Value"
echo %myvar%

to see results, save the batch and run the following from cmdline:

batchfile.cmd Default

Which will skip prompt and just echo:

Default

batchfile.cmd

Which will prompt Enter Value: just hit enter, which will then echo:

Default Value

Lastly

batchfile.cmd

and enter a value, which wil lecho the entered value.

6

The solutions proposed above did not work for me or they worked in a very clunky way.

This is (an obvious) simple solution to the problem I applied:

SET Docdir=D:\Documents\
SET /p Docdir="Target directory (Press Enter to keep <%Docdir%>): "

It results in the following prompt:

Target directory (Press Enter to use <D:\Documents\>):

User then see what's the default value and can accept it with Enter key

Not the answer you're looking for? Browse other questions tagged or ask your own question.