Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a command line parameter in a batch file

Is it possible to update or replace a command line parameter (like %1) inside of a batch file?

Sample code:

rem test.cmd
@echo off
echo Before %1
IF "%1" == "123" (
    set %%1 = "12345678"
)
echo After %1

Desired Result:

C:/>Test 123
Before 123
After 12345678

Actual Result:

C:/>Test 123
Before 123
After 123
like image 357
Veener Avatar asked Oct 18 '13 17:10

Veener


People also ask

How do I pass a command line argument to a batch file?

In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on. If you require all arguments, then you can simply use %* in a batch script.

What does @echo off do in a batch file?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

What is %% A in batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I modify a batch file?

Edit a batch file from within Windows Batch files are plain-text files, which means they can be edited as a text file by right-clicking the file and clicking Edit as shown in the picture. Once you've clicked edit, your default text editor opens the file and allows it to be modified.


2 Answers

No. What you are trying is not possible.

Can be simulated passing original batch parameters to subrutine, or call the same cmd recursively with modified parameters, which again get %1, %2, ... the parameters provided in the call. But this is not what you ask.

rem test.cmd
@echo off
echo Before %1

if "%~1"=="123" (
    call :test %1234
) else (
    call :test %1
)

goto :EOF

:test

echo After %1
like image 138
MC ND Avatar answered Oct 05 '22 21:10

MC ND


Argument variables are reserved, protected variables, you can't modify the content of one of those variables by yourself.

I suggest you to store the argument in a local variable then you can do all operations you want:

@echo off

Set "FirstArg=%~1"

Echo: Before %FirstArg%

IF "%FirstArg%" EQU "123" (
    Set "FirstArg=12345678"
)

Echo: After %FirstArg%

Pause&Exit
like image 20
ElektroStudios Avatar answered Oct 05 '22 23:10

ElektroStudios