0

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?

2 Answers 2

3

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 (
        ...
 )
Sign up to request clarification or add additional context in comments.

Comments

2

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!

3 Comments

True, I agree with Julien. If you enable delayed expansion then the SET /P will work inside a for block.
@djangofan - Actually, SET /P works regardless. It is only the display of the stored value that requires delayed expansion.
The if condition foo && bar should be written as if condition foo & bar. As originally written with &&, bar will only execute if foo was successfull. || is the conditional operator for failure. The simple command concatenation operator is a single &.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.