B

batch命令学习

轻松学习 技术 2023-08-14

学习编程时,有时要访问github,以及在使用一些加速代理时要配置hosts文件,所以最初就写了一个host.bat文件来写入,并且设置登录时自动运行。

@echo. >>C:\Windows\System32\Drivers\etc\hosts
@echo. >>C:\Windows\System32\Drivers\etc\hosts
@echo 43.128.3.53 www.notion.so >>C:\Windows\System32\Drivers\etc\hosts
@echo 43.128.3.53 msgstore.www.notion.so >>C:\Windows\System32\Drivers\etc\hosts
@echo 43.128.3.53 msgstore.www.notion.so >>C:\Windows\System32\Drivers\etc\hosts
@echo. >>C:\Windows\System32\Drivers\etc\hosts
@echo 13.250.177.223 github.com >>C:\Windows\System32\Drivers\etc\hosts

但是运行了一段时间,发现公司网域会不定期重置hosts文件,就导致要么我写进去的信息丢失,要么就是写进去了几十行。

所以考虑在bat加一个判定来解决问题。即如果行数少于某个值,那么就写入hosts文件,如果大于就代表已经写入过了,无需再调用。

@echo off
setlocal enabledelayedexpansion
set /a row=0
for /f "tokens=*" %%i in (C:\Windows\System32\drivers\etc\hosts) do (
set /a row+=1
)
if !row! LSS 50 call host.bat

这里有几个学习点:

  1. 一定要添加setlocal enabledelayedexpansion,不然会导致变量无法自加。
  2. batch文件大于小于不是用符号而是用英文符号

    EQU - 等于
    NEQ - 不等于
    LSS - 小于
    LEQ - 小于或等于
    GTR - 大于
    GEQ - 大于或等于
  3. set /a 与set /p分别是对应数学运算与 用户输入
  4. for循环语法 for %%i in( command) do command
  5. if %a% geq %b% () else () 使用if来判定来执行相应的命令
  6. call命令可以调用其他bat文件
PREV
教育的反思
NEXT
Git命令学习记录

评论(0)

发布评论