萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> 作業系統基礎知識

DOS 批次檔撰寫入門:核心指令與流程控制完整教學

批次檔(.bat/.cmd)是 Windows/DOS 自動化腳本的基礎。掌握 echo、if、goto、for、choice 等指令,即可撰寫強大的自動化流程。

基礎指令

指令功能範例
echo顯示訊息/開關指令回顯echo Hello / echo off
@單行隱藏指令回顯@echo off
call呼叫另一批次檔(返回繼續執行)call sub.bat
pause暫停並提示「按任意鍵繼續」pause
rem / ::註解行rem 這是註解

流程控制進階指令

IF 條件判斷(三種語法)

# 1. 字串比較
if "%1"=="a" format a:

# 2. 檔案存在判斷
if exist config.sys edit config.sys

# 3. 錯誤碼判斷(由大到小判斷)
if errorlevel 3 goto err3
if errorlevel 2 goto err2
if errorlevel 1 goto err1

GOTO 標籤跳轉

goto end
:end
echo 程式結束

CHOICE 互動選單

choice /c:yme "請選擇 [Y]es [M]aybe [N]o"
if errorlevel 3 goto no
if errorlevel 2 goto maybe
if errorlevel 1 goto yes

FOR 迴圈處理檔案集合

for %%f in (*.bat *.txt) do type %%f

批次檔中變數用 %%f,命令列直接執行用 %f。

完整範例:互動式工具選單

@echo off
:menu
cls
echo 1. 磁碟重組
echo 2. 顯示記憶體
echo 3. 結束
choice /c:123 /n "請選擇:"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag

:defrag
c:\dos\defrag
goto menu

:mem
mem
goto menu

:end
echo 再見!

除錯技巧

  • 執行時加 cmd /k test.bat 保留視窗觀察錯誤訊息。
  • 使用 echo on 開啟指令回顯追蹤流程。
  • 善用 setlocal enabledelayedexpansion 處理延遲變數展開(進階)。
copyright © 萬盛學電腦網 all rights reserved