Epligam
Epligam

Reputation: 783

Windows batch - ask for user input with default value

In a windows batch file I want to ask the user for an input, I want to show the user a default value which is the folder where the bat file reside. So when running the batch file the batch check the current folder and set the default variable to it then user can accept the suggested value by clicking on enter or enter a different value. i tried this code but it doesn't work, the UserInputPath is not set.

    set default=ABCD
    set /p UserInputPath=%default%
    echo %UserInputPath%

Upvotes: 8

Views: 14687

Answers (3)

Stephan
Stephan

Reputation: 56155

You asked for user can accept the suggested value by clicking on enter or enter a different value.

Take advantage of the behavior of set /p: if the input is empty (just ENTER), the variable keeps unchanged. So you can simply set a default value:

set "UserInputPath=ABCD"
set /p "UserInputPath=Enter path or just ENTER for default [%UserInputPath%] : "
echo %UserInputPath%

Upvotes: 11

user7818749
user7818749

Reputation:

Based on your edit of question. You want to use %~dp0 to detect the drive and path of the batch file, then echo the path into the prompt and set it as default, unless a user types in something else, it will always use the default path the batch is run from. Can be run as script value or as script only where the user will be prompted:

@echo off
set "UserInputPath=%1"
set "default=%~dp0"
if "%UserInputPath%"=="" set /p "UserInputPath=Enter Path (Default "%default%"): " || set "UserInputPath=%default%"
echo "%UserInputPath%"
pause

Upvotes: 4

aschipfl
aschipfl

Reputation: 34899

Replace the first line by set UserInputPath=ABCD, so when the user just confirms the prompt with ENTER, the former variable value is not going to be overwritten and so ABCD is going to be echoed:

set "UserInputPath=ABCD"
set /P UserInputPath="Prompt text: "
echo(%UserInputPath%

If you want to know whether the user typed anything, query the ErrorLevel value afterwards:

if ErrorLevel 1 echo The user just pressed {Enter}.

N. B.:
If you want the prompt to be prefilled with ABCD, then you need to use some external software that is capable of sending keystrokes to this prompt...

Upvotes: 10

Related Questions