有没有像“watch”这样的命令?或“inotifywait”在Mac上?

发布于 2024-08-06 19:58:24 字数 67 浏览 9 评论 0 原文

我想监视 Mac 上的一个文件夹,然后执行 bash 脚本,向其传递刚刚移入或在监视目录中创建的任何文件/文件夹的名称。

I want to watch a folder on my Mac and then execute a bash script, passing it the name of whatever file/folder was just moved into or created in the watched directory.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

够运 2024-08-13 19:58:24

fswatch

fswatch 是一个使用 Mac OS X FSEvents API 来监视事件的小程序目录。
当收到有关对该目录进行任何更改的事件时,指定的
shell 命令由 /bin/bash 执行

如果您使用的是 GNU/Linux,
inotifywatch(部分
大多数发行版上的 inotify-tools 包)提供了类似的
功能。

更新: fswatch 现在可以在许多平台上使用,包括 BSD、Debian 和 Windows。

语法/简单示例

可以监视多个路径的新方法 - 对于版本 1.x 及更高版本

fswatch -o ~/path/to/watch | xargs -n1 -I{} ~/script/to/run/when/files/change.sh

注意:如果没有 -I{}-o 输出的数字将添加到 xargs 命令的末尾。如果您选择使用该数字,请将 {} 放置在命令中的任意位置。

版本 0.x 的旧方法:

fswatch ~/path/to/watch ~/script/to/run/when/files/change.sh

使用 Homebrew 安装

自 2013 年 9 月 12 日起,它已添加回

brew install fswatch

不使用 Homebrew 安装

Terminal.app 中键入这些命令

cd /tmp
git clone https://github.com/alandipert/fswatch
cd fswatch/
make
cp fswatch /usr/local/bin/fswatch

如果您没有您的系统上的 c 编译器可能需要安装 Xcode 或 Xcode 命令行工具 - 两者都是免费的。但是,如果是这种情况,您可能应该查看自制程序

fswatch 版本 1.x 的附加选项

Usage:
fswatch [OPTION] ... path ...

Options:
 -0, --print0          Use the ASCII NUL character (0) as line separator.
 -1, --one-event       Exit fsw after the first set of events is received.
 -e, --exclude=REGEX   Exclude paths matching REGEX.
 -E, --extended        Use exended regular expressions.
 -f, --format-time     Print the event time using the specified format.
 -h, --help            Show this message.
 -i, --insensitive     Use case insensitive regular expressions.
 -k, --kqueue          Use the kqueue monitor.
 -l, --latency=DOUBLE  Set the latency.
 -L, --follow-links    Follow symbolic links.
 -n, --numeric         Print a numeric event mask.
 -o, --one-per-batch   Print a single message with the number of change events.
                       in the current batch.
 -p, --poll            Use the poll monitor.
 -r, --recursive       Recurse subdirectories.
 -t, --timestamp       Print the event timestamp.
 -u, --utc-time        Print the event time as UTC time.
 -v, --verbose         Print verbose output.
 -x, --event-flags     Print the event flags.

See the man page for more information.

fswatch

fswatch is a small program using the Mac OS X FSEvents API to monitor a directory.
When an event about any change to that directory is received, the specified
shell command is executed by /bin/bash

If you're on GNU/Linux,
inotifywatch (part of the
inotify-tools package on most distributions) provides similar
functionality.

Update: fswatch can now be used across many platforms including BSD, Debian, and Windows.

Syntax / A Simple Example

The new way that can watch multiple paths - for versions 1.x and higher:

fswatch -o ~/path/to/watch | xargs -n1 -I{} ~/script/to/run/when/files/change.sh

Note: The number output by -o will get added to the end of the xargs command if not for the -I{}. If you do choose to use that number, place {} anywhere in your command.

The older way for versions 0.x:

fswatch ~/path/to/watch ~/script/to/run/when/files/change.sh

Installation with Homebrew

As of 9/12/13 it was added back in to homebrew - yay! So, update your formula list (brew update) and then all you need to do is:

brew install fswatch

Installation without Homebrew

Type these commands in Terminal.app

cd /tmp
git clone https://github.com/alandipert/fswatch
cd fswatch/
make
cp fswatch /usr/local/bin/fswatch

If you don't have a c compiler on your system you may need to install Xcode or Xcode command line tools - both free. However, if that is the case, you should probably just check out homebrew.

Additional Options for fswatch version 1.x

Usage:
fswatch [OPTION] ... path ...

Options:
 -0, --print0          Use the ASCII NUL character (0) as line separator.
 -1, --one-event       Exit fsw after the first set of events is received.
 -e, --exclude=REGEX   Exclude paths matching REGEX.
 -E, --extended        Use exended regular expressions.
 -f, --format-time     Print the event time using the specified format.
 -h, --help            Show this message.
 -i, --insensitive     Use case insensitive regular expressions.
 -k, --kqueue          Use the kqueue monitor.
 -l, --latency=DOUBLE  Set the latency.
 -L, --follow-links    Follow symbolic links.
 -n, --numeric         Print a numeric event mask.
 -o, --one-per-batch   Print a single message with the number of change events.
                       in the current batch.
 -p, --poll            Use the poll monitor.
 -r, --recursive       Recurse subdirectories.
 -t, --timestamp       Print the event timestamp.
 -u, --utc-time        Print the event time as UTC time.
 -v, --verbose         Print verbose output.
 -x, --event-flags     Print the event flags.

See the man page for more information.
゛清羽墨安 2024-08-13 19:58:24

您可以使用 launchd 来实现此目的。 Launchd 可以配置为在文件路径修改时自动启动程序。

例如,当我的用户帐户的桌面文件夹被修改时,以下 launchd config plist 将启动程序 /usr/bin/logger

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>logger</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/logger</string>
        <string>path modified</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Users/sakra/Desktop/</string>
    </array>
</dict>
</plist>

要激活 config plist,请将其保存到 Library 文件夹中的 LaunchAgents 文件夹中作为“logger.plist”。

然后,您可以在 shell 中使用命令 launchctl 来激活 logger.plist,方法是运行:

$ launchctl load ~/Library/LaunchAgents/logger.plist

桌面文件夹现在正在受到监视。每次更改时,您都应该在 system.log 中看到输出(使用 Console.app)。
要停用 logger.plist,请运行:

$ launchctl unload ~/Library/LaunchAgents/logger.plist

上面的配置文件使用 WatchPaths 选项。或者,您也可以使用
QueueDirectories 选项。有关详细信息,请参阅 launchd 手册页。

You can use launchd for that purpose. Launchd can be configured to automatically launch a program when a file path is modified.

For example the following launchd config plist will launch the program /usr/bin/logger when the desktop folder of my user account is modified:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>logger</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/logger</string>
        <string>path modified</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Users/sakra/Desktop/</string>
    </array>
</dict>
</plist>

To activate the config plist save it to the LaunchAgents folder in your Library folder as "logger.plist".

From the shell you can then use the command launchctl to activate the logger.plist by running:

$ launchctl load ~/Library/LaunchAgents/logger.plist

The desktop folder is now being monitored. Every time it is changed you should see an output in the system.log (use Console.app).
To deactivate the logger.plist, run:

$ launchctl unload ~/Library/LaunchAgents/logger.plist

The configuration file above uses the WatchPaths option. Alternatively you can also use the
QueueDirectories option. See the launchd man page for more information.

你在看孤独的风景 2024-08-13 19:58:24

Facebook 的 watchman(可通过 Homebrew 获得)看起来也不错。它还支持过滤:

这两行在源目录上建立一个监视,然后设置
启动名为“buildme”的触发器,它将运行名为“minify-css”的工具
每当 CSS 文件发生更改时。该工具将传递一个列表
更改了文件名。

$watchman watch ~/src

$ watchman -- 触发 ~/src buildme '*.css' -- minify-css

注意,路径必须是绝对路径。

Facebook's watchman, available via Homebrew, also looks nice. It supports also filtering:

These two lines establish a watch on a source directory and then set
up a trigger named "buildme" that will run a tool named "minify-css"
whenever a CSS file is changed. The tool will be passed a list of the
changed filenames.

$ watchman watch ~/src

$ watchman -- trigger ~/src buildme '*.css' -- minify-css

Notice that the path must be absolute.

丶视觉 2024-08-13 19:58:24

您可能想看一下(或许还可以扩展)我的小工具 kqwait。目前它只是等待单个文件上的写入事件,但是 kqueue 架构允许用于分层事件堆叠...

You might want to take a look at (and maybe expand) my little tool kqwait. Currently it just sits around and waits for a write event on a single file, but the kqueue architecture allows for hierarchical event stacking...

对不⑦ 2024-08-13 19:58:24

watchdog 是一个跨平台的Python API,用于监视文件/目录,它有内置的“技巧”工具允许您在事件发生(包括新添加的文件、删除的文件和更改的文件)时触发操作(包括 shell 命令)。

watchdog is a cross-platform python API for watching files / directories, and it has builtin "tricks" tool that allows you to trigger actions (including shell commands) when events occur (including new added file, removed file and changed file).

寒冷纷飞旳雪 2024-08-13 19:58:24

这只是提到 entr 作为 OSX 上文件更改时运行任意命令的替代方案。我觉得它简单又有用。

  • 在 macos 上使用 brew install entr
  • 在 Debian/Ubuntu 上使用 apt install entr

This is just to mention entr as an alternative on OSX to run arbitrary commands when files change. I find it simple and useful.

  • brew install entr on macos
  • apt install entr on Debian/Ubuntu
花落人断肠 2024-08-13 19:58:24

这是使用 sschober工具

$ while true; do kqwait ./file-to-watch.js; script-to-execute.sh; done

Here's a one-liner using sschober's tool.

$ while true; do kqwait ./file-to-watch.js; script-to-execute.sh; done
ゃ人海孤独症 2024-08-13 19:58:24

苹果 OSX 文件夹操作允许您根据对文件夹执行的操作自动执行任务。

Apple OSX Folder Actions allow you to automate tasks based on actions taken on a folder.

ζ澈沫 2024-08-13 19:58:24

编辑: fsw 已合并到 fswatch。在此答案中,任何对 fsw 的引用现在都应为 fswatch

我用 C++ 编写了一个名为 fswfswatch 替代品,它具有多项改进:

  • 它是一个 GNU 构建系统项目,可以在任何支持的平台上构建(OS X v.> = 10.6) 与

    <预><代码>./configure &&制作&&须藤进行安装

  • 多个路径可以作为不同的参数传递:

    fsw 文件-0 ... 文件-n 
    
  • 它转储包含所有事件信息的详细记录,例如:

    2014 年 2 月 15 日星期六 00:53:45 - /path/to/file:inodeMetaMod 修改 isFile 
    
  • 它的输出很容易解析,以便fsw输出可以通过管道传输到另一个进程。 p>

  • 可以使用 -l, --latency 自定义延迟。
  • 可以使用 -n, --numeric 写入数字事件标志,而不是文本事件标志。
  • 可以使用 strftime 格式字符串和 -t, --time-format 自定义时间格式。
  • 时间可以是机器的本地时间(默认)或带有-u, --utc-time的UTC时间。

获取 fsw:

fsw 托管在 GitHub 上,可以通过克隆其存储库来获取:

    git clone https://github.com/emcrisostomo/fsw

安装fsw:

可以使用以下命令安装fsw

    ./configure && make && sudo make install

更多信息:

我还写了一篇介绍性博客文章,您可以在其中找到几个有关 fsw 工作原理的示例。

Edit: fsw has been merged into fswatch. In this answer, any reference to fsw should now read fswatch.

I wrote an fswatch replacement in C++ called fsw which features several improvements:

  • It's a GNU Build System project which builds on any supported platform (OS X v. >= 10.6) with

    ./configure && make && sudo make install
    
  • Multiple paths can be passed as different arguments:

    fsw file-0 ... file-n 
    
  • It dumps a detailed record with all the event information such as:

    Sat Feb 15 00:53:45 2014 - /path/to/file:inodeMetaMod modified isFile 
    
  • Its output is easy to parse so that fsw output can be piped to another process.

  • Latency can be customised with -l, --latency.
  • Numeric event flags can be written instead of textual ones with -n, --numeric.
  • The time format can be customised using strftime format strings with -t, --time-format.
  • The time can be the local time of the machine (by default) or UTC time with -u, --utc-time.

Getting fsw:

fsw is hosted on GitHub and can be obtained cloning its repository:

    git clone https://github.com/emcrisostomo/fsw

Installing fsw:

fsw can be installed using the following commands:

    ./configure && make && sudo make install

Further information:

I also wrote an introductory blog post where you can find a couple of examples about how fsw works.

失去的东西太少 2024-08-13 19:58:24

我的 fswatch 分支提供了 inotifywait -m 的功能,但稍微少了一些(没有等等,更多!我在 Linux 上遇到了更多麻烦 inotifywait...) 解析友好的输出。

它是对原始 fswatch 的改进,因为它通过 STDOUT 发送更改文件的实际路径,而不是要求您提供它派生的程序。

作为我用来自动化操作的一系列可怕的 bash 脚本的基础,它一直坚如磐石。

(这是题外话)另一方面,Linux 上的 inotifywait 需要在其之上进行大量的组装工作,尽管我认为我仍然没有找到管理它的好方法基于 node.js 的东西可能就是门票。

My fork of fswatch provides the functionality of inotifywait -m with slightly less (no wait, more! I have a lot more troubles on Linux with inotifywait...) parse-friendly output.

It is an improvement upon the original fswatch because it sends out the actual path of the changed file over STDOUT rather than requiring you to provide a program that it forks.

It's been rock solid as the foundation of a series of scary bash scripts I use to automate stuff.

(this is off-topic) inotifywait on Linux, on the other hand, requires a lot of kludges on top of it and I still haven't figured out a good way to manage it, though I think something based on node.js might be the ticket.

初与友歌 2024-08-13 19:58:24

我为此有一个 GIST,用法非常简单

watchfiles <cmd> <paths...>

为了说明这一点,每次 file1file2 更改时,以下命令都会回显 Hello World ;默认间隔检查为 1 秒

watchfiles 'echo Hello World' /path/to/file1 /path/to/file2 

如果我想每 5 秒检查一次,我可以使用 -t 标志

watchfiles -t 'echo Hello World' /path/to/file1 /path/to/file2 
  • -v 启用 verbose 模式显示调试信息
  • -q 使 watchfiles 安静地执行(将显示 #,以便用户可以看到程序正在执行)
  • - qq 使 watchfiles 完全安静地执行
  • -h 显示帮助和用法

https://gist.github.com/thiagoh/5d8f53bfb64985b94e5bc8b3844dba55

I have a GIST for this and the usage is pretty simple

watchfiles <cmd> <paths...>

To illustrate, the following command will echo Hello World every time that file1 OR file2 change; and the default interval check is 1 second

watchfiles 'echo Hello World' /path/to/file1 /path/to/file2 

If I want to check every 5 seconds I can use the -t flag

watchfiles -t 'echo Hello World' /path/to/file1 /path/to/file2 
  • -v enables the verbose mode which shows debug information
  • -q makes watchfiles execute quietly (# will be shown so the user can see the program is executing)
  • -qq makes watchfiles execute completely quietly
  • -h shows the help and usage

https://gist.github.com/thiagoh/5d8f53bfb64985b94e5bc8b3844dba55

清醇 2024-08-13 19:58:24

sudo fs_usage -f filesys | sudo fs_usage -f filesys | grep “有趣的事情”?

sudo fs_usage -f filesys | grep "interesting thing" ?

蓝色星空 2024-08-13 19:58:24

我最终为 macOS 做了这个。我确信这在很多方面都很可怕:

#!/bin/sh
# watchAndRun
if [ $# -ne 2 ]; then
    echo "Use like this:"
    echo "   $0 filename-to-watch command-to-run"
    exit 1
fi
if which fswatch >/dev/null; then
    echo "Watching $1 and will run $2"
    while true; do fswatch --one-event $1 >/dev/null && $2; done
else
    echo "You might need to run: brew install fswatch"
fi

I ended up doing this for macOS. I'm sure this is terrible in many ways:

#!/bin/sh
# watchAndRun
if [ $# -ne 2 ]; then
    echo "Use like this:"
    echo "   $0 filename-to-watch command-to-run"
    exit 1
fi
if which fswatch >/dev/null; then
    echo "Watching $1 and will run $2"
    while true; do fswatch --one-event $1 >/dev/null && $2; done
else
    echo "You might need to run: brew install fswatch"
fi
农村范ル 2024-08-13 19:58:24

如果你想使用 NodeJS,你可以使用一个名为 chokidar 的包(或 chokidar-cli 实际上)用于观看,然后使用 rsync (Mac 附带):

Rsync命令:

$ rsync -avz --exclude 'some-file' --exclude 'some-dir' './' '/my/destination'

Chokidar cli(通过 npm 全局安装):

chokidar \"**/*\" -c \"your-rsync-command-above\"

If you want to use NodeJS, you can use a package called chokidar (or chokidar-cli actually) for the watching and then use rsync (included with Mac):

Rsync command:

$ rsync -avz --exclude 'some-file' --exclude 'some-dir' './' '/my/destination'

Chokidar cli (installed globally via npm):

chokidar \"**/*\" -c \"your-rsync-command-above\"

雾里花 2024-08-13 19:58:24

我竭诚推荐使用 watchexec。内置 Rust,无论您使用哪个平台,It Just Works™!还有简单的 CLI 选项。

I can wholeheartedly recommend using watchexec. Built in Rust and It Just Works™ no matter which platform you're on! Straightforward CLI options as well.

剧终人散尽 2024-08-13 19:58:24

对于没有 watch 命令但希望每 3 秒执行一次命令的用户来说,这是一个简单的单行替代方案:


尽管 :;执行你的命令;睡觉3;完毕

这是一个无限循环,与执行以下操作基本相同:


watch -n3 你的命令

Here's a simple single line alternative for users who don't have the watch command who want to execute a command every 3 seconds:


while :; do your-command; sleep 3; done

It's an infinite loop that is basically the same as doing the following:


watch -n3 your-command

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文