web-dev-qa-db-ja.com

フォルダーを監視し、そこにファイルがある場合はコマンドを実行しますか?

UbuntuモニターFolder Aが欲しいです。 .shファイルがある場合、そのファイルをFolder Bに移動してバックグラウンドで実行したいと思います。これは可能ですか?それを実現するために何を使うべきですか?

3
Ignacio

いくつかのオプションがあります:

1. inotifywaitを使用する

#!/bin/bash
# set path to watch
DIR="/path/to/sourcedir"
# set path to copy the script to
target_dir="/path/to/targetdir"

inotifywait -m -r -e moved_to -e create "$DIR" --format "%f" | while read f

do
    echo $f
    # check if the file is a .sh file
    if [[ $f = *.sh ]]; then
      # if so, copy the file to the target dir
      mv "$DIR/$f" "$target_dir"
      # and rum it
      /bin/bash "$target_dir/$f" &
    fi
done

Inotifywaitの説明

オプションの設定

継続的にログを記録するには、オプション-mを設定する必要があります。

man inotifywaitから:

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

再帰的にログを記録するには、オプション-rを設定する必要があります。

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

再帰的な監視が必要ない場合は、オプションを削除してください。

イベント

さらに、トリガーするイベントを指定する必要があります:

EVENTS
       The following events are valid for use with the -e option:

       access A  watched  file  or  a file within a watched directory was read
              from.

       modify A watched file or a file within a watched directory was  written
              to.

       attrib The metadata of a watched file or a file within a watched direc‐
              tory was modified.  This includes timestamps, file  permissions,
              extended attributes etc.

       close_write
              A  watched file or a file within a watched directory was closed,
              after being opened in writeable mode.  This does not necessarily
              imply the file was written to.

       close_nowrite
              A  watched file or a file within a watched directory was closed,
              after being opened in read-only mode.

       close  A watched file or a file within a watched directory was  closed,
              regardless  of  how  it  was opened.  Note that this is actually
              implemented  simply  by  listening  for  both  close_write   and
              close_nowrite, hence all close events received will be output as
              one of these, not CLOSE.

       open   A watched file or a file within a watched directory was opened.

       moved_to
              A file or directory was moved into a  watched  directory.   This
              event  occurs  even  if the file is simply moved from and to the
              same directory.

       moved_from
              A file or directory was moved from a  watched  directory.   This
              event  occurs  even  if the file is simply moved from and to the
              same directory.

       move   A file or directory was moved from or to  a  watched  directory.
              Note  that  this is actually implemented simply by listening for
              both moved_to and moved_from, hence all  close  events  received
              will be output as one or both of these, not MOVE.

       move_self
              A  watched  file  or  directory was moved. After this event, the
              file or directory is no longer being watched.

       create A file or directory was created within a watched directory.

       delete A file or directory within a watched directory was deleted.

       delete_self
              A watched file or directory was deleted.  After this  event  the
              file  or  directory  is no longer being watched.  Note that this
              event can occur even if it is not explicitly being listened for.

       unmount
              The filesystem on which a watched file or directory resides  was
              unmounted.   After this event the file or directory is no longer
              being watched.  Note that this event can occur even if it is not
              explicitly being listened to.

-eを使用して、トリガーする各イベントを先頭に追加する必要があります。

-e moved_to -e create

もちろん、リストから任意のイベントトリガーを設定できます。

オプション--format "%f"を使用して、コマンド出力にfilenameを作成します。これは、設定されたパスと組み合わせて、ファイルのコピーと実行に使用します。

使い方

  1. Inotify-toolsをインストールします

    Sudo apt-get install intotify-tools
    
  2. スクリプトを空のファイルにコピーし、watch_dir.shとして保存します

  3. スクリプトの先頭で、監視するディレクトリとスクリプトをコピーするディレクトリの両方を設定します
  4. 実行すると、ディレクトリの監視が開始されます。

2. pythonを使用する

ただし、余分なものをインストールしなくても、小さなpythonスクリプトを使用して同じことを実行できます。

#!/usr/bin/env python3
import subprocess
import os
import time
import shutil

source = "/path/to/sourcedir"
target = "/path/to/targetedir"
files1 = os.listdir(source)

while True:
    time.sleep(2)
    files2 = os.listdir(source)
    # see if there are new files added
    new = [f for f in files2 if all([not f in files1, f.endswith(".sh")])]
    # if so:
    for f in new:
        # combine paths and file
        trg = os.path.join(target, f)
        # copy the file to target
        shutil.move(os.path.join(source, f), trg)
        # and run it
        subprocess.Popen(["/bin/bash", trg])
        print(trg)
    files1 = files2

使い方

  1. スクリプトを空のファイルにコピーし、watch_dir.pyとして保存します
  2. スクリプトの先頭で、ディレクトリを監視するように設定し、スクリプトを(source, target)にコピーします。
  3. 実行すると、ディレクトリの監視が開始されます。

注意

上記の両方のオプションは、スクリプトが引数を必要としないことを前提としていますが、これは明らかにこのようなセットアップの場合です。

5
Jacob Vlijm