Code Monkey home page Code Monkey logo

bat-test's Introduction

バッチファイルのテスト

set /p VARIABLE="please input: " でコンソールで入力した文字を配列に格納したくて試行錯誤したメモを残しておきます。

@echo off
setlocal enabledelayedexpansion

set NUM=0
:Input
set INPUT=
set /p INPUT="Please input: "
if defined INPUT (
    set STORE[%NUM%]=%INPUT%
    set /a NUM+=1
    goto :Input
)

echo.

if %NUM% equ 0 (
    echo No input.
) else (
    set /a NUM-=1
    for /l %%i in (0, 1, !NUM!) do (
        echo store[%%i] is !STORE[%%i]!
    )
)

解説

if defined VAR

変数 VAR に値が定義されていれば処理します。

set STORE[%NUM%]=%INPUT%

STORE[n] という疑似配列変数に入力値を格納します。

n は上記では set /a で計算して 1ずつ増加します。

for /l %%i in (初期値, 増加値, 終了値) do コマンド

/l で一般的な For ループを指定します。

%%i%% に英語 1文字を付けるのが決まりとのこと。

終了値までコマンドは実行されますので、1 減らしました。

!NUM!

!NUM!!STORE[%i%]! は遅延環境変数と呼ばれるもので、バッチの () 内のコマンド内の変数が最初に展開されてしまう仕様などを回避するために使っています。(使用するためには冒頭の setlocal enabledelayedexpansion が必要です。)

  • set /a NUM-=1 の結果をその後の For ループに反映させるために ! で括ります。
  • %STORE[%i%]% だと %STORE[%i%]% として分割されてしまうので、! で括ります。

参考:

bat-test's People

Contributors

ytabuchi avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.