How to initialize a variable in windows command shell? I tried

(
var $a=1
echo $a
)

and got an error

'var' is not recognized as an internal or external command, operable program or batch file.
有帮助吗?

解决方案

You can declare a variable in this way:

set MYVAR="value"

and echo it simply writing:

%MYVAR%

其他提示

I usually wrap the variable in percent signs...
set blah="hello"
echo %blah%

To protect against most poison characters, without including double quotes in the value itself, you can use the following (and then include the double quotes to echo or manipulate it later).

set "variable=123 & abc"
echo "%variable%"

Inside a loop you most often need to use delayed expansion, and !variable! syntax to use the variable, like so:

setlocal enabledelayedexpansion
for %%a in (1 2 3 a b c) do (
set "variable=%%a"
echo "!variable!"
)

Be aware that ! characters become a poison character when using delayed expansion.

set variable=12

echo %variable%
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top