下面兩個指令,請直接在指令列上練習~~ECHO Hello World!!>file.txt
把Hello World!!存到file.txt中;若檔案不存在,則會產生這一個file.txt檔案;若檔案已經存在,則把這一個檔案的內容清除。並且把Hello World!!存到檔案中ECHO Hello BAT!!>>file2.txt
把Hello World!!存到file2.txt中;若檔案不存在,則會產生這一個file2.txt檔案;若檔案已經存在,則在這一個檔案的內容最後加入Hello BAT!!
========== 測驗開始 ==========
1. 印出目前所在資料夾的名稱,例如,目前在C:\windows\newfile,則印出newfile
提示: GOTO, ECHO, FOR, %CD%
解答:
exercise_a.bat
@ECHO OFF
SET MYPATH=%CD%
:Search
FOR /F "tokens=1,* delims=\ " %%p IN ("%MYPATH%") DO (
SET MYPATH=%%~q
SET Current=%%~p
)
IF "%MYPATH%" NEQ "" GOTO :Search
ECHO %Current%
PAUSE
2. 若有一個設定檔為setting.ini,內容為
; This is setting file for test
; When ShowMoneyFlag is ON, the system will show money string
ShowMoneyFlag=OFF
; When ShowYou in ON, the system will show the username
ShowYou=ON
讓使用者透過修改setting.ini可以改變顯示的文字~並且把結果存到result.txt
提示: ECHO, FOR, IF, SET
解答:
exercise_b.bat
@ECHO OFF
FOR /F "eol=; tokens=1-2 delims==" %%i IN (setting.ini) DO (
SET %%~i=%%~j
)
IF /I "%ShowMoneyFlag%" EQU "ON" (
ECHO Show money!!
ECHO Show money!!>result.txt
) ELSE (
ECHO NoMoney!!
ECHO NoMoney!!>result.txt
)
IF /I "%ShowYou%" EQU "ON" (
ECHO Hello %UserName%
ECHO Hello %UserName%>>result.txt
)
PAUSE
7 則留言:
第一個example會停住ㄝ,什麼都沒顯示?
哪一個example.txt?
exercise_a.bat會停住ㄝ,什麼都沒顯示?
CLS
@ECHO OFF
ECHO.
SET MYPATH=%CD%
:_SEARCH
FOR /F "tokens=1,* delims=\ " %%p IN ("%MYPATH%") DO (
SET MYPATH=%%~q
SET CURRENT=%%~p
)
IF "%MYPATH%" NEQ "" GOTO :_SEARCH
ECHO "%CURRENT%"
:_END
ECHO.
PAUSE
IF /I "ShowYou"的判斷是fail的?
但是我用SET ShowYou看的結果是ON的ㄝ?
=============================
CLS
@ECHO OFF
ECHO.
:===== set variable (ShowMoneyFlag & ShowYOu)=====
FOR /F "eol=; tokens=1-2 delims==" %%i IN (setting.ini) DO (
: ECHO %%i %%j
SET %%~i == %%~j
)
SET ShowYou
SET ShowMoneyFlag
:===== delete existed result.txt =======
IF EXIST result.txt (
DEL result.txt
)
:===== echo ShowYou Variable =====
IF /I "%ShowYou%" EQU "ON" (
ECHO Hello %UserName%
ECHO Hello %UserName%>>result.txt
) ELSE (
ECHO NOT Equal
)
:_END
ECHO.
PAUSE
是SET %%~i=%%~j
不是
SET %%~i == %%~j
沒有空格,而且是只有一個等號
張貼留言