Папка монитора и команда выполнения, если существует файл там?

Я хотел бы иметь свой монитор Ubuntu Folder A. Если существует a .sh зарегистрируйте там, я хотел бы переместить тот файл в Folder B и выполненный это в фоновом режиме. Действительно ли это возможно? Что я должен использовать, чтобы заставить его произойти?

3
задан 15 March 2017 в 09:32

2 ответа

У Вас есть несколько опций:

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

Опции набора

Для входа continuesly необходимо установить опцию -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", мы заставляем команду произвести имя файла, которое мы будем использовать для того, чтобы скопировать и петлять, объединенные с путями набора.

Как использовать

  1. Inotify-инструменты установки

    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
ответ дан 1 December 2019 в 15:34

Вот еще одна версия с рекурсивным обходом дерева...

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

source = "/home/pi/Pictures/2020/"

def tree_walk(path):
    if os.path.isfile(path):
    if path.endswith("jpg"):
        subprocess.Popen(["/home/pi/git/rpi_scripts/telegram/tg_send_pic.sh", path])
        subprocess.Popen(["rm", path])
    elif path.endswith("mp4"):
        subprocess.Popen(["/home/pi/git/rpi_scripts/telegram/tg_send_video.sh", path])
        subprocess.Popen(["rm", path])
    else:
        print("other files...", path)
elif os.path.isdir(path):
    items = os.listdir(path)
    for i in items:
        trg = os.path.join(path, i)
        tree_walk(trg)
else:
    print(path, "spec file: socket, FIFO, device file etc.")

tree_walk(source)
#try:
#thread = threading.Timer(3, tree_walk(source))
#thread.start()
#except KeyboardInterrupt:
#    print("end")
0
ответ дан 11 July 2020 в 22:40

Другие вопросы по тегам:

Похожие вопросы: