keke's diary

おめでとうございます!

Windows の bat ファイル構文のメモ

Windows でたまに利用する bat ファイルの構文のメモ書き。

パスの判定

@echo off
IF "%~1"=="" (
  echo the argument is empty.
  exit /b
)
IF NOT EXIST %1 (
  echo the argument is not valid path.
  exit /b
)
IF EXIST %1\ (
  echo the argument is a directory.
)
IF NOT EXIST %1\ (
  echo the argument is a file.
)
C:\workdir>script.bat
the argument is empty.

C:\workdir>script.bat missing-file
the argument is not valid path.

C:\workdir>script.bat script.bat
the argument is a file.

C:\workdir>script.bat .\
the argument is a directory.

C:\workdir>

subroutine を利用する

@echo off
call :subroutine Alice %1
call :subroutine Bob %2
call :subroutine Alice %3
exit /b

:subroutine
echo %1 said "%2"
exit /b
C:\workdir>script.bat SYN SYN-ACK ACK
Alice said "SYN"
Bob said "SYN-ACK"
Alice said "ACK"

C:\workdir>

for 文にカウンタを付ける

@echo off
setlocal enabledelayedexpansion
set i=1
for %%f in (*) do (
  set s=00!i!
  set s=!s:~-3,3!
  set /a i=i+1
  echo !s! %%f
)
setlocal disabledelayedexpansion
C:\workdir>script.bat
001 file-01.txt
002 file-02.txt
003 script.bat

C:\workdir>