Linux watch 命令的 Windows 模拟是什么?

Pet*_*Law 79 windows linux command-line

我正在寻找一个像 Linuxwatch程序一样工作的 Windows 程序/脚本/命令行功能。

watch 定期调用另一个程序/任何内容并显示结果,这对于每秒刷新输出文件或类似文件非常有用:

watch cat my-output.txt
Run Code Online (Sandbox Code Playgroud)

或者,更有力地:

watch grep "fail" my-output.txt
Run Code Online (Sandbox Code Playgroud)

我在 cygwin 的库中寻找过它,但它似乎不存在。

har*_*ymc 60

自己写。假设文件watch.bat包含:

@ECHO OFF
:loop
  cls
  %*
  timeout /t 5 > NUL
goto loop
Run Code Online (Sandbox Code Playgroud)

并通过例如调用它:

watch echo test
Run Code Online (Sandbox Code Playgroud)

test每 5 秒回显一次。


小智 39

Powershell 有“while”命令。您可以像在 Linux 中一样使用它:

而 (1) {your_command; 睡觉 5}

Linux版本:

虽然是真的;做你的命令;睡眠5; 完毕

其他:

while ($true) {netstat -an | findstr 23560; 睡5;日期}

  • 你可以只使用 `while (1)`,因为 `1` 是真的。 (5认同)
  • 我还发现您可以使用“clear”作为最后一个语句,因此它的行为更像是 watch。 (3认同)

Dav*_*ett 19

watch在 Cygwin 中可用,在此处procps列出的包中(可以通过网站上的包搜索找到此信息,此处)。我不认为这个包是由默认的 cygwin 安装程序安装的,但我通常在新安装时选择它,以便让 watch 命令可用。

软件包中工具的位置通常与 Linux 发行版中的软件包名称相匹配(watchDebian 和 Ubuntu 上的软件包也包含procps),因此如果 Cygwin 软件包搜索功能失败,Linux 发行版的信息可能会提供线索。


小智 18

一个通用的 Windows 命令 oneliner 来完成这个:

for /l %g in () do @( echo test & timeout /t 2 )
Run Code Online (Sandbox Code Playgroud)

将“echo test”替换为您希望重复运行的命令。


小智 8

这就是我在 PowerShell 中的做法:

while(1){ netstat -an|grep 1920;start-sleep -seconds 2;clear }
Run Code Online (Sandbox Code Playgroud)

条件while(1)等价于while true,无限循环。


小智 8

我写了这个小的 PowerShell 模块来做你想要的。把它放进去

C:\Users\[username]\Documents\WindowsPowerShell\Modules\Watch
Run Code Online (Sandbox Code Playgroud)

import-module watch在 PowerShell 中运行。


# ---- BEGIN SCRIPT
# Author:       John Rizzo
# Created:      06/12/2014
# Last Updated: 06/12/2014
# Website:      http://www.johnrizzo.net

function Watch {
    [CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact='High')]
    param (
        [Parameter(Mandatory=$False,
                   ValueFromPipeline=$True,
                   ValueFromPipelineByPropertyName=$True)]
        [int]$interval = 10,

        [Parameter(Mandatory=$True,
                   ValueFromPipeline=$True,
                   ValueFromPipelineByPropertyName=$True)]
        [string]$command
    )
    process {
        $cmd = [scriptblock]::Create($command);
        While($True) {
            cls;
            Write-Host "Command: " $command;
            $cmd.Invoke();
            sleep $interval;
        }
    }
}

Export-ModuleMember -function Watch

# --- END SCRIPT
Run Code Online (Sandbox Code Playgroud)


Eri*_*ikW 7

这是一个 PowerShell one liner:

while ($true) { <your command here> | Out-Host; Sleep 5; Clear }
Run Code Online (Sandbox Code Playgroud)