How to check geo IP data from a remote URL in a batch script?
I try to create a bat file to check country by IP, but I don't understand what's wrong. The logic is to grep curl output, if US|CA|MX found, then !var! not empty, then echo "You live in North America". The problem is that !var! not empty every time. Maybe you know any other ways to check IP geo from cmd without powershell?
@echo off
setlocal ENABLEDELAYEDEXPANSION
FOR /F "tokens=* USEBACKQ" %%F IN (`curl -k https://freegeoip.app/xml/ ^| findstr "US CA MX"`) DO (
SET var=%%F
)
if not !var! == "" (echo "You live in North America") else (echo "qwerty")
endlocal
Solution 1:
@echo off && setlocal
for /f "delims=>< tokens=3 usebackq" %%F in (`
2^>^&1 curl -# -k https://freegeoip.app/xml/ ^| findstr "RJ SP GO"`)do set "_var=%%~F"
if defined _var (
echo "You live in Brazil"
)else echo\"qwerty"
endlocal
Try to change your for loop and be more specific, add a delimiter and a token to get the strings in the correct place if they exist in curl
output...
> curl -# -k https://freegeoip.app/xml/ 2>&1
<Response>
<IP>187.111.14.73</IP>
<CountryCode>BR</CountryCode>
<CountryName>Brazil</CountryName>
<RegionCode>RJ</RegionCode>
<RegionName>Rio de Janeiro</RegionName>
<City>Sao Goncalo</City>
<ZipCode>24400</ZipCode>
<TimeZone>America/Sao_Paulo</TimeZone>
<Latitude>-22.8192</Latitude>
<Longitude>-43.0402</Longitude>
<MetroCode>0</MetroCode>
</Response>
Use "delims=>< tokens=3
to find >RJ<
in <RegionCode>RJ</RegionCode>
with findstr "RJ SP GO"
One precisely try would be:
@echo off && setlocal
for /f "delims=>< tokens=3 usebackq" %%F in (
`2^>^&1 curl -# -k https://freegeoip.app/xml/ ^| ^
find "/RegionCode" ^| findstr "RJ SP GO"`)do set "_var=%%~F"
if defined _var (
echo "You live in Brazil"
)else echo\"qwerty"
endlocal
A shorter option with no variable/for loop:
@echo off
2>&1 curl -# -k https://freegeoip.app/xml/|find "/RegionCode"|findstr "RJ SP GO">nul && (
echo "You live in Brazil") || echo\"qwerty"