0

I am trying to pass an array to a conca.bat file so I can concatenate all the strings that list or array has. I have been able to concatenate, buty just if I put the Array by hand, but I am not able to do it when I pass ii from command line...

It works:

FOR %%i IN (12346,49874,48954) DO call :concat %%i
set var=%var%%1;

Doesn´t work

FOR %%i IN %1 DO call :concat %%i
set var=%var%%1;

What is the structure I must follow from the command prompt?

conca.bat "12346,49874"

or

conca.bat {12346,49874}

1 Answer 1

1

There are no real lists or arrays in CMD. However, if I've understood your question correctly, you are trying to do something like this:

concat.bat 123 456 789

and want the output to be 123456789. If this is the case, SHIFT is the magic command you are looking for. This should do it:

@ECHO OFF
SET concatString=
:LOOP
IF [%1]==[] GOTO ENDLOOP
SET concatString=%concatString%%1
SHIFT
GOTO LOOP
:ENDLOOP
ECHO %concatString%
PAUSE

When you pass parameters to a bat file via command line, they are accessible via %1, %2, %3 and so in. This means for concat.bat a b c that %1 is a, %2 is b and %3 is c. The only problem is that we might not know how many parameters there will be and you want your script to work with only one parameter as well as with 100 of them. At this point SHIFT is saving the day.

SHIFT does one simple thing. It moves the index of the parameters to the right, so the "old" %1 disappears, %2 becomes %1, %3 becomes %2 and so on. We just keep on looping until the last passed parameter becomes %1. After another shift there is no value left which can be assigned to %1 so [%1]==[] becomes true and we jump out of the loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Using if [%1]==[] is the worst way you can use. At least use if "%1"=="" to avoid problems with characters like ,;<space><>|&=. Or use if "%~1"=="" to avoid also problems when the argument can be enclosed with quotes

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.