
在 Windows7 shell 中,我有以下工作代碼來列印目前的 IP 位址:
@echo off
:: get ipv4
ipconfig | findstr IPv4 | findstr 172 > ipadd.txt
:: For statement to find the numbers
for /F "tokens=13" %%i in (ipadd.txt) do (
echo %%i
)
del ipadd.txt /Q
但是,我不希望列印 IP 位址,而是將其儲存在變數中,如下(不起作用)程式碼片段所示:
@echo off
:: get ipv4
ipconfig | findstr IPv4 | findstr 172 > ipadd.txt
:: For statement to find the numbers
for /F "tokens=13" %%i in (ipadd.txt) do (
set ip=%%i
)
del ipadd.txt /Q
echo IP is $ip
預期輸出是(範例)
IP位址是123.456.7.8
實際輸出是
IP 是 $ip
如何解決這個問題?
答案1
您已用 [bash] 標記您的問題。你是不是為 Bourne shell 編寫腳本bash
或sh
任何類似 Bourne shell 的東西。 Windows 批次腳本通常在cmd.exe
shell(MS-DOS 的後代)上執行COMMAND.COM
,並且具有完全不同的語法。
尤其,%name%
, 不是$name
,是 Windows 和 MS-DOS 批次腳本中變數的語法。
echo IP is %ip%
當你這樣做時:
for /F "tokens=13" %%i in ('ipconfig | findstr IPv4 | findstr 172') do (