Home>

I created a batch file that uses the following array, but it doesn't work as expected.
Please let me know if you know how to fix it.

Operating environment: Windows8.1 Enterprise
Specification app: Command Prompt

-Bat file contents -----------------------
set ftpIPAddress [0] = xx.aa.bb.cc
set ftpFileName [0] = ftp11.txt

set ftpIPAddress [1] = xx.aa.bb.dd
set ftpFileName [1] = ftp12.txt

echo off

echo.
for/l %% n in (0,1,1) do (

call echo open %% ftpIPAddress [%% n] %%>%% ftpFileName [%% n] %%
call echo user >>%% ftpFileName [%% n] %%
call echo pass >>%% ftpFileName [%% n] %%
call echo put ftpcheck.txt /data/ftpcheck/ftpcheck20191121_%%n.txt >>%% ftpFileName [%% n] %%

)


Expected behavior
fpt11.txt
ftp12.txt
Is created.

Current behavior
% ftpFileName [0]%
% ftpFileName [1]%
Is created.

The contents of the file are as intended.

  • Answer # 1

    There are no arrays because the variables used in the batch file are environment variables anyway.
    Even if it is written with [], it is treated as a variable name.
    However, it seems that it can be handled like an array for the purpose seen.
    I think it will look something like this:

    setlocal enabledelayedexpansion
    set ftpIPAddress [0] = xx.aa.bb.cc
    set ftpFileName [0] = ftp11.txt
    set ftpIPAddress [1] = xx.aa.bb.dd
    set ftpFileName [1] = ftp12.txt
    echo off
    echo.
    for/l %% i in (0,1,1) do (
    set/a n = %% i
    call set ip = %% ftpIPAddress [! n!] %%
    call set fn = %% ftpFileName [! n!] %%
    echo open! ip!>! fn!
    echo user >>! fn!
    echo pass >>! fn!
    echo put ftpcheck.txt /data/ftpcheck/ftpcheck20191121_!n!.txt >>! fn!
    )

  • Answer # 2

    The redirect file name is determined beforecallis executed.
    Assuming you don't useenabledelayedexpansion,
    Option 1:

    for/l %% n in (0,1,1) do (
      cmd/c "echo open %% ftpIPAddress [%% n] %%>%% ftpFileName [%% n] %%"
      cmd/c "echo user >>%% ftpFileName [%% n] %%"
      cmd/c "echo pass >>%% ftpFileName [%% n] %%"
      cmd/c "echo put ftpcheck.txt /data/ftpcheck/ftpcheck20191121_%%n.txt >>%% ftpFileName [%% n] %%"
    )


    Option 2:

    for/l %% n in (0,1,1) do call: sub %% n
    exit/b
    : sub
    call set FN = %% ftpFileName [% 1] %%
    call echo open %% ftpIPAddress [% 1] %%>% FN%
    call echo user >>% FN%
    call echo pass >>% FN%
    call echo put ftpcheck.txt /data/ftpcheck/ftpcheck20191121_%1.txt >>% FN%
    exit/b

  • Answer # 3

    Arrays cannot be used in BAT files.
    Let's rethink from that point