macos Mac 上是否有“watch”或“inotifywait”之类的命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1515730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:27:37  来源:igfitidea点击:

Is there a command like "watch" or "inotifywait" on the Mac?

macoswatchinotify

提问by Mint

I want to watch a folder on my Mac (Snow Leopard) and then execute a script (giving it the filename of what was just moved into a folder (as a parameter... x.sh "filename")).

我想在我的 Mac (Snow Leopard) 上观看一个文件夹,然后执行一个脚本(给它刚刚移动到文件夹中的文件名(作为参数... x.sh“文件名”))。

I have a script all written up in bash (x.sh) that will move some files and other stuff on input $1 I just need OSX to give me the file name when new files/folders are moved/created into a dir.

我有一个全部用 bash (x.sh) 编写的脚本,该脚本将在输入 $1 上移动一些文件和其他内容,当新文件/文件夹移动/创建到目录时,我只需要 OSX 给我文件名。

Any such command?

有这样的命令吗?

回答by cwd

fswatch

fswatch

fswatchis 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

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

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

如果您使用的是 GNU/Linux, inotifywatchinotify-tools大多数发行版中的软件包的一部分 )提供了类似的功能。

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

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

Syntax / A Simple Example

语法 / 一个简单的例子

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

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

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

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

注:由输出数量-o将被添加到年底xargs,如果不是命令-I{}。如果您确实选择使用该编号,请将其{}放置在您的命令中的任何位置。

The older way for versions 0.x:

版本 0.x的旧方法:

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

Installation with Homebrew

使用 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:

截至 2013 年 9 月 12 日,它已重新添加到自制软件中- 是的!因此,更新您的公式列表 ( brew update),然后您需要做的就是:

brew install fswatch

Installation without Homebrew

没有 Homebrew 的安装

Type these commands in Terminal.app

输入这些命令 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 ccompiler 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.

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

Additional Options for fswatchversion 1.x

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.

回答by sakra

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

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

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

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

<?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".

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

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

然后,您可以在 shell 中使用该命令launchctl通过运行以下命令来激活 logger.plist:

$ 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:

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

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

The configuration file above uses the WatchPathsoption. Alternatively you can also use the QueueDirectoriesoption. See the launchdman page for more information.

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

回答by Jakub Holy

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

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

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

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

$ watchman watch ~/src

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

Notice that the path must be absolute.

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

回答by sschober

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 kqueuearchitecture allows for hierarchical event stacking...

您可能想看看(并可能扩展)我的小工具kqwait。目前它只是坐在那里等待单个文件上的写入事件,但kqueue架构允许分层事件堆叠......

回答by gfxmonk

watchdogis 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).

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

回答by Donny Winston

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

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

回答by Joshua Cook

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

这是一个使用sschober's tool 的单线

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

回答by Enrico M. Crisostomo

Edit:fswhas been merged into fswatch. In this answer, any reference to fswshould now read fswatch.

编辑:fsw已合并到fswatch. 在这个答案中,任何参考fsw现在都应该阅读fswatch.

I wrote an fswatchreplacement in C++ called fswwhich features several improvements:

fswatch用 C++写了一个替代品,fsw它有几个改进:

  • 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 fswoutput 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 strftimeformat strings with -t, --time-format.
  • The time can be the localtime of the machine (by default) or UTC time with -u, --utc-time.
  • 这是一个 GNU 构建系统项目,它构建在任何受支持的平台 (OS X v. >= 10.6) 上,具有

    ./configure && make && sudo make install
    
  • 多个路径可以作为不同的参数传递:

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

    Sat Feb 15 00:53:45 2014 - /path/to/file:inodeMetaMod modified isFile 
    
  • 它的输出很容易解析,因此fsw输出可以通过管道传输到另一个进程。

  • 延迟可以自定义-l, --latency
  • 数字事件标志可以用-n, --numeric.
  • 时间格式可以使用strftime带有-t, --time-format.
  • 时间可以是机器的本地时间(默认情况下)或 UTC 时间-u, --utc-time

Getting fsw:

获取 fsw:

fswis hosted on GitHuband can be obtained cloning its repository:

fsw托管在GitHub上,可以得到克隆其存储库:

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

Installing fsw:

安装 fsw:

fswcan be installed using the following commands:

fsw可以使用以下命令安装:

    ./configure && make && sudo make install

Further information:

更多信息:

I also wrote an introductory blog postwhere you can find a couple of examples about how fswworks.

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

回答by Steven Lu

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

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

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

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

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

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

(this is off-topic) inotifywaiton 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.jsmight be the ticket.

(这是题外话)inotifywait另一方面,在 Linux 上需要很多杂物,我仍然没有想出一个很好的方法来管理它,尽管我认为基于的东西node.js可能是票证。

回答by Asaph

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

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