Как использовать inotifywait для наблюдения за каталогом на предмет создания файлов определенного расширения

возможно, это поможет вам после установки imagemagick

, а затем попробуйте следующее;

 montage foo1.jpg foo2.jpg montage.jpg | lpr -o number-up=2  montage.jpg
22
13.04.2017, 15:36
5 ответов

как мне изменить команду inotifywait, чтобы она сообщала только тогда, когда файл создается определенный тип / расширение

Обратите внимание, что это непроверенный код , поскольку у меня сейчас нет доступа к inotify . Но что-то похожее на это должно сработать:

inotifywait -m /path -e create -e moved_to |
    while read path action file; do
        if [[ "$file" =~ .*xml$ ]]; then # Does the file end with .xml?
            echo "xml file" # If so, do your thing here!
        fi
    done
32
27.01.2020, 19:42

Используйте двойное отрицание:

inotifywait -m --exclude "[^j][^s]$" /path -e create -e moved_to |
    while read path action file; do
        echo "The file '$file' appeared in directory '$path' via '$action'"
    done

Это будет включать только файлы javascript

10
27.01.2020, 19:42

--include и --includei являются фактическими опциями в мастер-версии двоичных файлов по крайней мере:

https://github.com/inotify-tools/inotify-tools/tree/master

11
27.01.2020, 19:42

В моем случае я пытался отфильтровать вывод inotifywaitс помощью чего-то вроде grep, чтобы дождаться создания одного файла с определенным расширением. Проблема с этим подходом в том, что grep просто зависнет.

По какой-то причине сигнал SIGPIPE либо не отправляется, либо не обрабатывается inotifywait. Я нашел этот вопрос, который столкнулся с той же проблемой, что и у меня, и замену процесса можно использовать в качестве обходного пути:

grep -E.*iso -m1 < <(inotifywait -qm -e create.)

Замена процесса не работает в некоторых оболочках (, например. sh), так что это работает не во всех случаях.


Из других ответов я не смог найти опцию включения --. Я, вероятно, буду экспериментировать с --exclude.

0
19.08.2020, 17:32

Начиная с версии 3.20.1 inotifywait вы можете использовать опцию --include.

пример inotifywait с--include

Вот пример использования --includeдля запуска сценария при добавлении файла wav в каталог.

#!/bin/sh

# Usage
#
# Call the script with the directory you want to watch as an argument. e.g.:
# watchdir.sh /app/foo/
#
#
# Description:
# Uses inotifywait to look for new files in a directory and process them:
# inotifywait outputs data which is passed (piped) to a do for subcommands.
#
#
# Requirements:
# Requires inotifywait which is part of inotify-tools.
# e.g. yum install -y inotify-tools or apt-get install -y inotify-tools.
#
#
# See also:
# https://linux.die.net/man/1/inotifywait
# https://github.com/inotify-tools/inotify-tools/wiki#info
# (Might be interested in pyinotify too.)


echo "Watch $1 for file changes..."


# Be careful not to confuse the output of `inotifywait` with that of `echo`.
# e.g. missing a `\` would break the pipe and write inotifywait's output, not
# the echo's.
inotifywait \
  $1 \
  --monitor \
  -e create \
  --timefmt '%Y-%m-%dT%H:%M:%S' \
  --format '%T %w %f %e' \
  --include "\.wav" \
| while read datetime dir filename event; do
  echo "Event: $datetime $dir$file $event"
  echo "Now, we could pass $datetime $dir $filename and $event to some other command."

  echo "Here's the extensionless filename:" ${filename%.*}
  echo "And the extension if needed:" ${filename##*.}

  python3 /app/phono.py --custom $dir$filename $dir${filename%.*}.txt /tmp/${filename%.*}
done


# --format:
#   %T  Replaced with the current Time in the format specified by the --timefmt option, which should be a format string suitable for passing to strftime(3).
#   %w  This will be replaced with the name of the Watched file on which an event occurred.
#   %f  When an event occurs within a directory, this will be replaced with the name of the File which caused the event to occur. Otherwise, this will be replaced with an empty string.
#   %e  Replaced with the Event(s) which occurred, comma-separated.
#   %Xe Replaced with the Event(s) which occurred, separated by whichever character is in the place of 'X'.
#
# There's no --include option, but there's --exclude, which can be used to the same effect as an include.


# test the script by creating a file in the watched directory, e.g.
# touch /app/foo/file1.wav # will trigger the script
# touch /app/foo/file1.txt # will not trigger the script

Установка (или компиляция )инструментов inotify -

inotifywait является частью инструментов inotify -. Вы можете установить его обычным способом, например.:

apt-get install -y inotify-tools

или

yum install -y inotify-tools

Но если в репозиториях доступны только более старые версии, вы можете скомпилировать из исходного кода. Если да:

cd /tmp/inotify-tools/
wget https://github.com/inotify-tools/inotify-tools/releases/download/3.20.2.2/inotify-tools-3.20.2.2.tar.gz
tar xzvf inotify-tools-3.20.2.2.tar.gz
cd inotify-tools-3.20.2.2
./configure --prefix=/usr --libdir=/lib64
make
make install
5
25.08.2020, 12:18

Теги

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