Member Avatar for Member #564502

Hi Guys,
I've got a small issue passing the string from command line parameter into the variable within the script.
An issue is when the parameter contains an equal mark in the string that brakes the line and the everything after an equal mark is missing. See an example:

script.bat

username=%1
password=%2

echo %username%
echo %password%

::END_SCRIPT

When I run the script as follow:

c:\script.bat John mypass&*(+=word&*
John
mypass&*(+

As you can observe everything after "=" mark has been skipped and variable %password% returns only part of the string mypass&*(+ and word&* is missing.

My question is whether can it be fixed some how and pass the string containing "=" mark from parameter into variable within the script?

Any help, feedback would be appreciated.
Cheers!!
emarcel.

Dani AI

Generated

The actual cause is the command shell, not the equals sign. Unquoted metacharacters (for example: &, |, <, >, parentheses) are interpreted by CMD as separators or operators, so the command line is split or reinterpreted before the batch sees the full string. showed the symptom and correctly pointed toward keeping the argument intact; the following practical options make that reliable inside a batch file.

A robust script-side approach is to accept a quoted argument and remove the enclosing quotes when assigning the variable. Example:

set "password=%~2"
echo %password%

The %~2 removes surrounding double quotes from the second positional parameter. Using set "name=value" avoids accidental trailing spaces.

If quoting on the command line is not desirable, metacharacters can be escaped with a caret (^) so CMD does not split the command (for instance escaping & as ^&). That works for isolated characters but becomes fragile for long strings that contain many special characters. Also note that if delayed expansion is enabled, literal ! characters need special handling or toggling of delayed expansion, because ! is processed by the parser.

Quick troubleshooting tips: echo all received arguments with echo %* to see how the shell parsed them, and use echo %~n to inspect values with surrounding quotes removed. For most cases, passing the value quoted and using %~n inside the batch is the simplest, most reliable method.

Recommended Answers

All 3 Replies

use double quotes to pass the values. But take care that quotes would also be taken as part of value

Member Avatar for Member #564502

Thanks! it works now:)

Cheers!!
emarcel

Thanks! it works now:)

Cheers!!
emarcel

Welcome sir!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.