在Linux中,如何在文件创建后立即将其移动到另一个目录?

在Linux中,如何在文件创建后立即将其移动到另一个目录?

我想将一个目录中创建的所有 *.xxx 文件移动到另一个目录。但是,我希望一旦创建文件,它们就应该移动到另一个目录。请帮忙。提前致谢。

答案1

  1. 在您的发行版上安装该inotify-tools软件包。
  2. 使用该命令inotifywait在所需目录上创建连续查找。前任:inotifywait -m -r -e create /src_dir。这个工具可以观察文件系统的其他方面(属性更改、关闭写入、移动、删除),所以,让我们继续创建文件。
  3. 使用此命令准备通知并持续运行,并使用具有足够权限的用户执行此命令:

    inotifywait -m -r -e create /src_dir |
    while read file; do
          mv /src_dir/*.xxx /dst_dir
    done
    

详细解释:

  • inotifywait- 使用 inotify API 的命令。提供监视文件系统事件的机制。man inotify了解更多详情。
  • -m-inotifywait第一个事件发生后继续运行。
  • -r- 递归运行。如果您不希望出现此行为,请将其删除。
  • -e create- 通知确定的事件。我们使用的是create。省略此参数可监视所有已知事件
  • /src_dir- 被监控地点的参数
  • |- 管道操作员。将一个命令输出重定向到另一个命令输出。
  • /while (...) done- 将所有名为 *.xxx 的内容移动/src_dir到名为 的目的地/dst_dir。该循环将确保每次命令触发事件时都会发生此移动inotifywait

从 man mapges 中提取:

-m, --monitor
Instead  of  exiting  after  receiving  a single event, execute indefinitely.  
The default behaviour is to exit after the first event occurs.

-e <event>, --event <event>
Listen for specific event(s) only.  The events which can be listened for are 
listed in the EVENTS section.  This option can be speci‐fied more than once.  
If omitted, all events are listened for.

-r, --recursive
Watch all subdirectories of any directories passed as arguments.  Watches will be
set up recursively to an unlimited depth.  Symbolic links are not traversed.
 Newly created subdirectories will also be watched.

相关内容