Reputation: 12174
When using set /p
inside this if block. The variable input
is not set to the input value. It is set only on second invocation of the script (as if it was set only after echo %input%
line).
if "%1"=="" (
echo "You have to specify the name of the file."
set /p input=File name:
echo %input%
pause
) else (
...
)
What can I do to have variable input
set to values which was actually entered?
Upvotes: 0
Views: 81
Reputation: 2246
You need to use delayed expansion.
In the Batch language, inside a FOR or a IF, the variables are "expanded" before and not during command execution. ( expanded = the variable is remplaced by its value )
For example, the following IF test
IF condition (
foo
bar
)
is interpreted as if condition foo & bar
So if a variable is set in foo
and this same variable is used in bar, it's the previous value of the variable ( the one before entering the loop ) that is used in bar
.
It's kinda disturbing but that how Batch works...
So ithe set
is working correctly, it's just a special way of working.
You must write SETLOCAL ENABLEDELAYEDEXPANSION
at the beginning of your code and the variable whose expansion should be delayed must be surrounded by !
instead of %
.
So echo %input%
become echo !input!
Upvotes: 2
Reputation: 37589
you don't need delayed expansion
here. Example:
if "%1"=="" (
echo "You have to specify the name of the file."
set /p input=File name:
call echo %%input%%
pause
) else (
...
)
Upvotes: 3