Watch for file linux

Команда watch Linux

Иногда возникает необходимость запускать ту или иную команду несколько раз. К примеру, если были замечены неполадки в работе сервера и есть основания полагать, что их причина кроется в использовании памяти либо выполнении операций ввода и вывода. Также это может понадобиться для отслеживания изменений в каталогах. Во всех этих и других случаях на помощь придет команда watch.

По умолчанию команда watch linux включена почти во все дистрибутивы Linux. Ее задача — запускать указанную пользователем команду через определенные промежутки времени и печатать вывод этой команды в окне терминала. Работу watch можно сравнить с работой tail, с той лишь разницей, что источником вывода является не файл журнала, а другая команда.

Команда watch в Linux

Синтаксис и опции

Синтаксис команды watch крайне прост:

watch опции команда_для_вывода

Перечень опций невелик, но их достаточно для эффективного использования команды:

  • -d (—differences) — служит для выделения тех данных в выводе команды, которые отличаются от предыдущих.
  • -n (—interval seconds) — позволяет установить желаемый интервал запуска команды.
  • -t (—no-title) — выключает отображение заголовков.
  • -b (—beep) — если при выполнении команды возникнет ошибка, будет подан звуковой сигнал.
  • -e (—errexit) — при возникновении ошибки вывод данных будет заморожен, команда watch прекратит работу после нажатия комбинации клавиш.
  • -g (—chgexit) — выход при условии, что в выводе команды обнаружатся изменения.
  • -c (—color) — интерпретирует последовательность цветов и стилей ANSI.
  • -x (—exec) — выполнение команды будет передано интерпретатору sh -c поэтому, возможно, вам придется использовать дополнительные кавычки чтобы добиться желаемого эффекта. При использовании полной версии написания (—exec) команда будет выполняться в с помощью утилиты exec.

Примеры использования watch

Проще всего продемонстрировать работу команды watch, наблюдая за тем, как компьютер использует оперативную память:

В данном случае не были использованы опции команды watch, зато к выполняемой команде free пришлось добавить параметр -m, который отвечает за отображение свободной памяти RAM. Так тоже можно и нужно делать, чтобы получить искомый результат.

Читайте также:  Переустановка аудио драйвера linux

Чтобы не запоминать каким был предыдущий результат вывода и не отслеживать изменения самостоятельно, стоит поручить эту работу опции -d. Она подсвечивает ту информацию, которая отличается от предыдущей:

На каждом из скриншотов в верхней строке есть надпись «Every 2,0s». Она означает, что программа перезапускается каждые 2 секунды. Этот интервал установлен по умолчанию, но его можно изменить, используя опцию -n.

watch -n5 -d ‘cat /proc/loadavg’

Обратите внимание на то, что значение -n не может быть меньше 1. Верхняя планка не ограничена.

Если возникла необходимость получить на экране терминала больше места для полезных данных, можно убрать заглавную информацию. Для этого предназначена опция -t.

Интервал обновления, опции команды и текущая дата больше не отображаются.

Что касается выхода из утилиты watch, то он осуществляется при нажатии клавиш Ctrl+C или Ctrl+Z. Пока пользователь не воспользуется одной из этих комбинаций, команда будет выполняться с заданными параметрами.

Выводы

Команда watch linux — это простой и эффективный инструмент для всех, кто занимается администрированием серверов. Впрочем, и обычные пользователи могут найти ей применение. Если у вас возникли вопросы относительно использования watch на компьютерах с установленной операционной системой Linux, задавайте их в комментариях.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Watchman – A File and Directory Watching Tool for Changes

Watchman is an open source and cross-platform file watching service that watches files and records or performs actions when they change. It is developed by Facebook and runs on Linux, OS X, FreeBSD, and Solaris. It runs in a client-server model and employs the inotify utility of the Linux kernel to provide a more powerful notification.

Useful Concepts of Watchman

  • It recursively watches watch one or more directory trees.
  • Each watched directory is called a root.
  • It can be configured via the command-line or a configuration file written in JSON format.
  • It records changes to log files.
  • Supports subscription to file changes that occur in a root.
  • Allows you to query a root for file changes since you last checked, or the current state of the tree.
  • It can watch an entire project.

In this article, we will explain how to install and use watchman to watch (monitor) files and record when they change in Linux. We will also briefly demonstrate how to watch a directory and invoke a script when it changes.

Читайте также:  Linux shutdown after hour

Installing Watchman File Watching Service in Linux

We will install watchman service from sources, so first install these required dependencies libssl-dev, autoconf, automake libtool, setuptools, python-devel and libfolly using following command on your Linux distribution.

----------- On Debian/Ubuntu ----------- $ sudo apt install autoconf automake build-essential python-setuptools python-dev libssl-dev libtool ----------- On RHEL/CentOS ----------- # yum install autoconf automake python-setuptools python-devel openssl-devel libssl-devel libtool # yum groupinstall 'Development Tools' ----------- On Fedora ----------- $ sudo dnf install autoconf automake python-setuptools openssl-devel libssl-devel libtool $ sudo dnf groupinstall 'Development Tools'

Once required dependencies installed, you can start building watchman by downloading its github repository, move into the local repository, configure, build and install it using following commands.

$ git clone https://github.com/facebook/watchman.git $ cd watchman $ git checkout v4.9.0 $ ./autogen.sh $ ./configure $ make $ sudo make install

Watching Files and Directories with Watchman in Linux

Watchman can be configured in two ways: (1) via the command-line while the daemon is running in background or (2) via a configuration file written in JSON format.

To watch a directory (e.g ~/bin ) for changes, run the following command.

Watch a Directory in Linux

The following command writes a configuration file called state under /usr/local/var/run/watchman/-state/, in JSON format as well as a log file called log in the same location.

You can view the two files using the cat command as show.

$ cat /usr/local/var/run/watchman/aaronkilik-state/state $ cat /usr/local/var/run/watchman/aaronkilik-state/log

You can also define what action to trigger when a directory being watched for changes. For example in the following command, ‘ test-trigger ‘ is the name of the trigger and ~bin/pav.sh is the script that will be invoked when changes are detected in the directory being monitored.

For test purposes, the pav.sh script simply creates a file with a timestamp (i.e file.$time.txt ) within the same directory where the script is stored.

time=`date +%Y-%m-%d.%H:%M:%S` touch file.$time.txt

Save the file and make the script executable as shown.

To launch the trigger, run the following command.

$ watchman -- trigger ~/bin 'test-trigger' -- ~/bin/pav.sh

Create a Trigger on Directory

When you execute watchman to keep an eye on a directory, its added to the watch list and to view it, run the following command.

View Watch List

To view the trigger list for a root, run the following command (replace ~/bin with the root name).

Читайте также:  Linux read only folder

Show Trigger List for a Root

Based on the above configuration, each time the ~/bin directory changes, a file such as file.2019-03-13.23:14:17.txt is created inside it and you can view them using ls command.

Test Watchman Configuration

Uninstalling Watchman Service in Linux

If you want to uninstall watchman, move into the source directory and run the following commands:

$ sudo make uninstall $ cd '/usr/local/bin' && rm -f watchman $ cd '/usr/local/share/doc/watchman-4.9.0 ' && rm -f README.markdown

For more information, visit the Watchman Github repository: https://github.com/facebook/watchman.

You might also like to read these following related articles.

Watchman is an open source file watching service that watches files and records, or triggers actions, when they change. Use the feedback form below to ask questions or share your thoughts with us.

Источник

How to monitor file content while they change in Linux

Monitoring file changes in a real time is very easy to do task in Linux System.

Directory, files, logs, etc. Changes can be easily monitored in real time with the help of watch command.

Watch is easy to use program to monitor changes in file or directory in Linux. It’s come by pre installed in all debain and arch based Linux System.

Check Watch is in system or not

Execute below command to know watch command is properly working in your system or not.

watch -v

Right now 3.3.16 is the latest version of watch. May be when you reading these post version will be changed.

Monitor files in the current directory

To monitor real time changes in current directory simple execute below code it will automatically changes, when there is new directory or file created.

watch ls

Above screen will be change, when there is any changes appear in User Directory.

Monitor disk spaces and highlight the changes

Below commad highlight where ever there is changes in Filesystem, 1k-blocks, Used, Available, User and Mounted on in free disk space command.

watch -d df

Watch real time changes in text file

Below command display live changes in file.txt. When ever user edit in file every changes will display in screen.

watch cat file.txt

Innovative tech mind with 12 years of experience working as a computer programmer, web developer, and security researcher. Capable of working with a variety of technology and software solutions, and managing databases.

Источник

Оцените статью
Adblock
detector