0

Is there any possibility to set variable "Message1 & Message2" and echo that variable?

For example:

set var=Message1 ^& Message2
echo %var%

It shows that "Message2" is not a command.

(if you put "echo Message1 ^& Message2" it will shows "Message1 & Message2" normally.)

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Mayuna
  • 21
  • 2
  • 10
  • 1
    Use `set "var=Message1 ^& Message2"` in first line to define the message with `^` and `&` assigned to `var`. Then the caret character is also on line `echo Message1 ^& Message2` on execution and `^` is interpreted as escape character for the ampersand. I recommend also reading answer on [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/a/26388460/3074564) – Mofi Oct 11 '18 at 15:25

3 Answers3

4

You need to add quotes like this

set "var=Message1 ^& Message2"
echo %var%
RGuggisberg
  • 4,630
  • 2
  • 18
  • 27
3

you have various options:

@echo off
set var=Message1 ^^^& Message2
echo a %var%

set "var=Message1 ^& Message2"
echo b %var%

set "var=Message1 & Message2"
echo c %var:&=^&%
Stephan
  • 53,940
  • 10
  • 58
  • 91
1

If you use the quoted syntax of the set command (which requires the command extensions to be enabled, but that is the default anyway) and use delayed expansion, you do not even have to escape anything:

set "var=Message1 & Message2"
setlocal EnableDelayedExpansion
echo(!var!
endlocal
aschipfl
  • 33,626
  • 12
  • 54
  • 99