批處理中的 echo 命令
- 批處理使用
echo命令 - 使用
echo命令列印訊息 -
echo批處理檔案中的新行或空白行 -
echo文字到檔案中 - 使用
echo命令回顯變數 - 回顯系統路徑
- 使用帶有轉義命令字元的
echo命令 - まとめ
在 Windows 中,echo 命令在命令列上顯示訊息。除了 Command shell 和 PowerShell,它還可以在許多其他作業系統 shell 中使用,例如 DOS、OS/2、ReactOS 和其他 Unix 和類 Unix 作業系統。
如今,它主要用於 shell 指令碼和批處理檔案。讓我們討論 Batch 的 echo 命令及其選項。
批處理使用 echo 命令
echo 命令是一個內部命令,用於列印螢幕上的文字或開啟或關閉命令回顯。它不設定 errorlevel 或清除 errorlevel。
在執行批處理檔案時執行的每個命令都會與輸出一起顯示在命令列上。當我們執行一個批處理檔案時,所有的命令都是按順序逐行執行的。
使用 echo 命令,即使使用 echo 命令本身,我們也可以關閉命令提示符中命令的回顯。
語法:
echo [on | off] echo <message> echo /? on- 顯示命令和輸出。off- 隱藏命令並且只顯示輸出。message- 要列印的文字。
如果你在沒有任何引數或選項的情況下鍵入 echo,它將顯示 echo 命令的狀態(即開啟或關閉)。在批處理檔案中,它主要用於關閉命令的回顯並僅顯示輸出,而 echo on 命令在除錯批處理檔案時很有用。
要檢查 echo 命令或 echo 設定的狀態,請在命令提示符下執行以下命令。
echo 輸出:

要關閉命令的回顯,請在批處理檔案的頂部新增 echo off。
echo off ipconfig PAUSE 
輸出:

但是,上述命令將在命令提示符中顯示 echo off 行。要隱藏此行,請在 echo off 的開頭新增@。
@echo off ipconfig PAUSE 
輸出:

使用 echo 命令列印訊息
echo 命令還可以在批處理檔案中執行命令時顯示訊息。
@echo off echo hello world echo this is an example of how to print a message using the echo command. cmd /k 
輸出:

你還可以在同一個批處理檔案中同時使用 echo on 和 echo off。有時,你可能需要關閉某些命令的回顯並開啟其他命令的回顯。
在這種情況下,你可以同時使用 echo on 和 echo off,如下例所示。
@echo off echo hello world echo Here, the echoing is turned off i.e. no commands are shown. @echo on echo Hello echo Here, the echoing is on i.e. commands are shown along with the output cmd /k 
輸出:

echo 批處理檔案中的新行或空白行
要在批處理檔案中回顯新行或在單獨的行中顯示訊息,在命令之間使用 echo. 或 echo:來新增一個新的行。這兩個命令的輸出將是相同的。
示例 - 1:
@echo off echo hello echo: echo world echo this will add a blank line between hello and world cmd /k 
示例 - 2:
@echo off echo hello echo. echo world echo this will add a blank line between hello and world cmd /k 
輸出:

echo 文字到檔案中
要將訊息回顯到文字檔案中,請執行以下命令。
echo this line will be saved to a text file > testfile.txt 
你也可以使用 echo 命令建立一個空檔案。要建立一個空檔案,請執行以下命令。
echo. 2>testfile.txt 
使用 echo 命令回顯變數
要使用 echo 命令回顯變數,請執行以下命令:
ECHO %OS% cmd /k 
建議使用 echo:代替下面給出的空格,儘管它有一些限制。但是,兩者的輸出將相同。
ECHO:%OS% cmd /k 這是因為如果你使用空格,它可能會以 echo on 或 echo off 的形式執行命令,而不是顯示變數的值。如下例所示,如果變數的值設定為關閉,使用空格會將其視為 echo off 並關閉回顯。
相反,如果我們使用 echo:,它只會顯示變數的值。
示例 - 1:
Set test=OFF Echo %test% echo echo is turned off instead of displaying the value cmd /k 
輸出:

示例 - 2:
Set test=OFF Echo:%test% echo the value is displayed 
輸出:

回顯系統路徑
要在新行中回顯路徑中的每個專案,請執行以下命令。
ECHO:%PATH:;= & ECHO:% 
輸出:

使用帶有轉義命令字元的 echo 命令
當你將 echo 命令與命令字元一起使用時,例如重定向(&)和管道(|,on,off)字元,預設情況下,命令字元將位於 echo 之前命令。為了避免這種情況,我們需要在使用命令字元時使用轉義字元(:、^)。
分別在每個命令字元的命令字元前新增轉義字元。
@echo off ECHO Here, the escape character is used for the ^& character like Mickey ^& Mouse ECHO file1 ^| file2 ^| file3 
輸出:

まとめ
我們已經討論了 echo 命令並涵蓋了幾乎所有內容以及示例。出於各種原因,它是一個非常有用的命令,用於批處理檔案,如上面的示例中所述。