I am trying to make a file that asks for your username and password, with a registration. When registering, the passwords are saved in variables.
The problem is i have
You method have an important drawback: How do you know how many different variables are you managing? How do you know that the next user will use user2
variable and the next one user3
? You must agree that if there is just one user then password variable don't require the user name and could be named just pass
, right?
The standard method to deal with this situation is via an array: you use a variable with same name (the array) and select different values from it via a subscript. In your case, you may have two arrays: user
and pass
, both with the same numeric subscript starting from 1. For example:
@echo off
setlocal EnableDelayedExpansion
set index=0
:nextUser
set /A index+=1
set /P "user[%index%]=Username: "
set /P "pass[%index%]=Password: "
rem Display data of user[1]:
echo %user[1]%'s password is %pass[1]%
rem Display data of all users, from 1 to %index%
for /L %%i in (1,1,%index%) do (
echo !user[%%i]!'s password is !pass[%%i]!
)
You may read a detailed description about array management in Batch files at this post: Arrays, linked lists and other data structures in cmd.exe (batch) script
You can use "delayed expansion" to solve the problem of the nested variables. For example, !%user1%pass!
: the !
is like %
but signals that expansion should be delayed, so %user1%
will be expanded first, leaving you with !johnpass!
which can be expanded next.
Here's a complete script:
@echo off
setlocal enabledelayedexpansion
set /p "user1=Username: "
set /p "%user1%pass=Password: "
echo %user1%'s password is !%user1%pass!