Tails linux

head command syntax in Linux

head ... ...

Example 10: As mention earlier print first 10 lines.

# head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin

Example 11: Print first two lines of a file.

# head -n 2 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin

Example 12: this option lets you print all lines starting from a line number you specify, unlike Example 11 which will show you the first number of lines you provided.

head -n <number of lines preceeded with "-"> /path/to/file

Example :

# head -n -27 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync

As you can notice, in this example, it printed all the lines starting after line 27.

5 практических примеров команды Tail в Linux

Давайте узнаем, как использовать команду tail в Linux с некоторыми практическими примерами. Мы будем использовать этот текстовый файл в этой статье:

Если вы используете команду tail без какой-либо опции, она будет печатать последние 10 строк. Это поведение по умолчанию команды tail.

Если файл имеет менее десяти строк, он отображает только доступные строки. Если последние несколько строк пусты, они все равно будут считаться допустимыми.

Но вам не нужно довольствоваться использованием команды tail по умолчанию. Это еще не все. Давайте рассмотрим наиболее частое использование хвостовых команд по одному.

1. Распечатайте последние N строк с помощью команды tail

Чтобы просмотреть последние N строк, вместо 10 по умолчанию вы можете использовать команду tail следующим образом:

Например, если вы хотите увидеть последние 5 строк с командой tail в нашем файле примера, вы можете использовать его следующим образом:

2. Распечатайте все строки, начиная с номера строки N

Если вы хотите просмотреть все строки, начинающиеся с номера строки N, вы можете использовать здесь опцию +.

В нашем примерном файле, если вы хотите увидеть все строки, начиная с строки 7, вы можете использовать его следующим образом:

3. Использование нескольких файлов с командой tail

Команда tail позволяет вам одновременно использовать несколько файлов. Все стандартные опции команды tail применимы к нескольким файлам.

Результат объединяется для всех файлов, и по умолчанию имя файла отображается в строках, начинающихся с «==>».

Например, если вы хотите увидеть последние три строки файлов sherlock.txt и agatha.txt, это будет выглядеть так:

Предположим, у вас есть файл, и к нему добавлен новый контент. Команда tail позволяет вам отображать все новые строки по мере их добавления в файл.

Для этого вы можете использовать опцию -f.

Команда сначала отобразит последние 10 строк файлов, а затем обновит вывод, когда новые строки будут добавлены в файл.

Это широко используется для просмотра файлов журнала в реальном времени. Это, пожалуй, наиболее практическое использование команды tail.

5. Использование команды tail с pipes

Команда tail может использоваться в сопряжении с другими командами с использованием pipes.

Например, если у вас слишком много файлов в каталоге, и вы хотите видеть только последние 3 измененных файла, вы можете использовать его следующим образом:

В приведенной выше команде ls -lrt перечисляет все файлы в обратном хронологическом порядке. И тогда команда tail дополнительно анализирует этот вывод и отображает только последние три строки вывода команды ls, и поэтому мы получаем список из трех последних измененных файлов.

Бонусный совет: покажите вывод команды tail с номерами строк

Номера строк помогают в понимании и анализе вывода. Предположим, вы отобразили последние 20 строк файла, но вы также хотите увидеть их номера строк, чтобы вы могли видеть общие строки в файле.

К сожалению, нет встроенной опции для отображения вывода команды tail с числами.

Но это не означает, что вы не можете отображать номера строк с помощью команды tail. Для этого вы можете использовать мощность труб. Вы только что видели в предыдущем разделе, что команды tail могут использоваться с трубами. Почему бы не использовать его здесь.

nl – способ отображения содержимого файла с номерами строк. Если вы объедините его с командой tail с помощью pipe, вы получите отображение команды tail с номерами строк.

Надеюсь, вы найдете примеры команд tail полезными. Если у вас есть какие-либо предложения или вопросы, поделитесь им в разделе комментариев ниже.

Options

Option Description
-c [+]num,—bytes=[+]num Output the last num bytes of each file.You can also use a plus sign before num to output everything starting at byte num. For instance, -c +1 will print everything.A multiplier suffix can be used after num to specify units: b (512), kB (1000), K (1024), MB (1000*1000), M (1024*1024), GB (1000*1000*1000), G (1024*1024*1024), and so on for T (terabyte), P (petabyte), E (exabyte), Z (zettabyte), Y (yottabyte).
-f,—follow[={name|descriptor}] This option will cause tail will loop forever, checking for new data at the end of the file(s). When new data appears, it will be printed.If you follow more than one file, a header will be printed to indicate which file’s data is being printed.If the file shrinks instead of grows, tail will let you know with a message.If you specify name, the file with that name is followed, regardless of its file descriptor.If you specify descriptor, the same file is followed, even if it is renamed. This is the default behavior.
-F «Follow and retry». Same as using —follow=name —retry.
-n num,—lines=num Output the last num lines, instead of the default (10).If you put a plus sign before num, tail will output all lines beginning with that line. For example, -n +1 will print every line.
—max-unchanged-stats=num If you are following a file with -f or —follow=name, tail continuously checks the file to see if its size has changed. If the size has changed, it reopens the file and looks for new data to print. The —max-unchanged-stats option reopens a file, even if its size has not changed, after every num checks.This option is useful if the file might be spontaneously unlinked or renamed, such as when log files are automatically rotated.
—pid=pid When following with -f or —follow, terminate operation after process ID pid dies.
-q,—quiet,—silent Never output headers.
—retry Keep trying to open a file even if it is temporarily inaccessible; useful with the —follow=name option.
-s num,—sleep-interval=num When following with -f or —follow, sleep for approximately num seconds between file checks. With —pid=pid, check process pid at least once every num seconds.
-v,—verbose Always print headers.
—help Display a help message, and exit.
—version Display version information, and exit.

Защищаем данные, отбрасываем хвост

Сам по себе наш персистентный раздел уже зашифрован. Однако у него есть существенный недостаток: он не обеспечивает правдоподобное отрицание наличия зашифрованных данных. Чтобы обеспечить правдоподобное отрицание, я предложу решение, которое отличается от рекомендаций создателей Tails. Как поступить тебе — решай сам.

Создатели Tails рекомендуют использовать cryptsetup, основанный на LUKS. Эта программа позволяет создавать скрытые разделы, однако такой раздел скрыт не до конца. Насколько мне известно, существует возможность обнаружить заголовок скрытого раздела, что позволяет установить его наличие.

Такой скрытый раздел лично меня не устраивает. Поэтому я решил использовать старый добрый TrueCrypt версии 7.1а. Заголовок скрытого раздела TrueCrypt неотличим от случайных данных, и, насколько мне известно, обнаружить его невозможно. Двоичный файл программы TrueCrypt лучше хранить здесь же, в персистентном разделе.

Детально описывать процесс создания двойного криптоконтейнера я не стану, отмечу лишь важный нюанс. Поскольку скрытый раздел TrueCrypt по-настоящему скрытый, о его существовании не догадывается даже сама программа, пока ты не введешь нужный пароль. Из-за этого при записи файлов в ложный раздел скрытый раздел может быть поврежден. Чтобы этого не произошло, при монтировании ложного раздела для записи на него картинок котиков нужно выбрать Mount Options → Protect hidden volume when mounting outer volume.

Подобно ящерице, которая при опасности отбрасывает свой хвост, мы теперь в случае необходимости сможем ввести пароль от фальшивого раздела и продемонстрировать всем фотографии котиков вместо конфиденциальной информации.

File monitoring

tail has two special command line option and (follow) that allows a file to be monitored. Instead of just displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display. This is particularly useful for monitoring log files. Ancient versions of tail poll the file every second by default but tail from the GNU coreutils as of version 7.5 support the inotify infrastructure introduced in Linux kernel version 2.6.13 on August 2005 which only check the file when is notified of changes by the kernel.

The following command will display the last 10 lines of messages and append new lines to the display as new lines are added to messages:

tail -f /var/adm/messages

To keep following the log even when it is recreated, renamed, or removed as part of log rotation, at least BSD and GNU implementations provide a option which is useful in cases when the user is following a log file that rotates.

tail -F /var/adm/messages

To interrupt tail while it is monitoring, break-in with Ctrl+C. This command can be run «in the background» with , see job control.

If the user has a command’s result to monitor, the watch command can be used.

There is a GNU Emacs mode that emulates the functionality of , called auto-revert-tail-mode.

COLOPHON top

       This page is part of the coreutils (basic file, shell and text
       manipulation utilities) project.  Information about the project can
       be found at ⟨http://www.gnu.org/software/coreutils/⟩.  If you have a
       bug report for this manual page, see
       ⟨http://www.gnu.org/software/coreutils/⟩.  This page was obtained
       from the tarball coreutils-8.32.tar.xz fetched from
       ⟨http://ftp.gnu.org/gnu/coreutils/⟩ on 2020-08-13.  If you discover
       any rendering problems in this HTML version of the page, or you
       believe there is a better or more up-to-date source for the page, or
       you have corrections or improvements to the information in this
       COLOPHON (which is not part of the original manual page), send a mail
       to man-pages@man7.org

GNU coreutils 8.32               March 2020                          TAIL(1)

Pages that refer to this page:
head(1), 
pmcd(1), 
pmdalogger(1), 
pmdasystemd(1), 
pmdaweblog(1)

Начало работы

После загрузки с рабочей флешки нам потребуется создать постоянный (persistent) защищенный раздел, своеобразный «жесткий диск на флешке». Это делается через Application → Tails → Configure Persistence.

Перезагружаем компьютер и на загрузочном экране выбираем Use Persistence и More Options, после чего вводим пароль для нашего хранилища.

Из меню внизу экрана выбираем регион

Это важно, поскольку от региона зависят входные узлы Tor. Здесь следует поэкспериментировать

В моем случае лучшим выбором оказалась Дания.

В меню расширенных настроек задаем пароль для программ, которым нужны права администратора. Можешь поставить любой, он работает в рамках сессии и ни на что больше не влияет.

Имей в виду, что загрузка занимает некоторое время, а потом Tails еще несколько минут будет подключаться к Tor. Отслеживать процесс можно, щелкнув по иконке Onion Circuits — луковичке в верхнем правом углу экрана.

Спустя некоторое время Tails проинформирует об успешном подключении к Tor. По умолчанию сеть сконфигурирована так, что весь трафик будет проходить через него. Теперь можно скачать все, что нам нужно для работы.

The head Command

The syntax of the head command is pretty straightforward:

Let’s prepare a file (numbers_en.txt) as the input example to understand the command better:

The file contains English words of numbers from 1 to 100. Thus, the file has 100 lines.

The head command will, by default, write the first ten lines of the input file to the standard output:

3.1. Output a Specific Number of Lines

With the -n option, we can let the head command output the first n lines instead of the default 10.

For example, if we want to have the first seven lines printed to standard out, we’d use -n 7:

If we pass the -n option together with a number following the –, for example -n -x, the head command will print all lines but the last x lines of the file. 

For instance, if we want to ignore the last 97 lines from the file, we’d do -n -97:

3.2. Output a Specific Number of Bytes

In addition to displaying text by line, the head command can also print the file content by byte if we pass the -c option.

The usage of the -c option is the same as the -n option except for displaying text byte-wise instead of line-wise.

Let’s see an example of displaying only the first word “one” (3 bytes) from the file:

3.3. Output Multiple Files

The head command can also handle multiple files. To see this, let’s first prepare another input file numbers_de.txt. This file is very similar to the numbers_en.txt. The only difference is that the words in the file are in German instead of English:

Now let’s output the first five lines from both files in one shot:

Команда tail в Linux

Перед тем как мы будем рассматривать примеры tail linux, давайте разберем ее синтаксис и опции. А синтаксис очень прост:

$ tail опции файл

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

  • -c — выводить указанное количество байт с конца файла;
  • -f — обновлять информацию по мере появления новых строк в файле;
  • -n — выводить указанное количество строк из конца файла;
  • —pid — используется с опцией -f, позволяет завершить работу утилиты, когда завершится указанный процесс;
  • -q — не выводить имена файлов;
  • —retry — повторять попытки открыть файл, если он недоступен;
  • -v — выводить подробную информацию о файле;

В качестве значения параметра -c можно использовать число с приставкой b, kB, K, MB, M, GB, G T, P, E, Z, Y. Еще есть одно замечание по поводу имен файлов. По умолчанию утилита не отслеживает изменение имен, но вы можете указать что нужно отслеживать файл по дескриптору, подробнее в примерах.

Использование tail

Теперь, когда вы знаете основные опции, рассмотрим приемы работы с утилитой. Самый простой пример — выводим последние десять строк файла:

Если вам недостаточно 10 строк и нужно намного больше, то вы можете увеличить этот параметр с помощью опции -n:

Когда вы хотите отслеживать появление новых строк в файле, добавьте опцию -f:

Вы можете открыть несколько файлов одновременно, просто перечислив их в параметрах:

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

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

Если вас интересует не число строк, а именно число байт, то вы можете их указать с помощью опции -c:

Для удобства, вы можете выбирать не все строки, а отфильтровать интересующие вас:

Особенно, это полезно при анализе логов веб сервера или поиске ошибок в реальном времени. Если файл не открывается, вы можете использовать опцию retry чтобы повторять попытки:

Как я говорил в начале статьи, по умолчанию опция -f или —follow отслеживает файл по его имени, но вы можете включить режим отслеживания по дескриптору файла, тогда даже если имя измениться, вы будете получать всю информацию:

The tail Command

The syntax of using the tail command is quite straightforward, too:

The tail command will by default write the last ten lines of the input file to the standard output:

4.1. Output a Specific Number of Lines

With the -n option, we can let the tail command output the last n lines instead of the default 10.

This example shows how to get the last seven lines from the input file:

If we pass the -n option together with a number following the “+”, for example “-n +x”, the tail command will print starting with the x-th line till the end of the file.

Let’s print from 95th line till the end of the numbers_en.txt file:

4.2. Output a Specific Number of Bytes

Similar to the head command, if we pass -c x option to the tail command, it will output only the last x bytes from the input file.

Let’s get the last number 100 from the input file:

In the example above, we passed 4 instead of 3 to the -c option. This is because there is an ending linebreak in the last line, and this linebreak occupied 1 byte.

4.3. Output Multiple Files

Like the head command, the tail command can output from multiple input files, too.

Let’s have a look at an example of printing the last five lines from two input files:

4.4. Watch a File for Changes

Sometimes the input file we want to check is changing. For example, a running application may append its output to a log file.

If we execute the tail command with the -f option on the changing file, all newly added lines will be appended to standard out.

Next, let’s see a demonstration of this feature.

First, we’ll create a simple shell script append_ts.sh. Every second it appends the current timestamp to a log file (/tmp/timestamp.log), it will append to the log file ten times:

Now, let’s start watching the log file by the tail command, then we execute the script above and observe if the newly append timestamps come to tail‘s output:

As we expected, all newly appended lines are printed out.

To exit the tail command, we can press Ctrl-C.

DESCRIPTION top

       Print the last 10 lines of each FILE to standard output.  With more
       than one FILE, precede each with a header giving the file name.

       With no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are mandatory for short options
       too.

       -c, --bytes=+]NUM
              output the last NUM bytes; or use -c +NUM to output starting
              with byte NUM of each file

       -f, --follow[={name|descriptor}]
              output appended data as the file grows;

              an absent option argument means 'descriptor'

       -F     same as --follow=name --retry

       -n, --lines=+]NUM
              output the last NUM lines, instead of the last 10; or use -n
              +NUM to output starting with line NUM

       --max-unchanged-stats=N
              with --follow=name, reopen a FILE which has not

              changed size after N (default 5) iterations to see if it has
              been unlinked or renamed (this is the usual case of rotated
              log files); with inotify, this option is rarely useful

       --pid=PID
              with -f, terminate after process ID, PID dies

       -q, --quiet, --silent
              never output headers giving file names

       --retry
              keep trying to open a file if it is inaccessible

       -s, --sleep-interval=N
              with -f, sleep for approximately N seconds (default 1.0)
              between iterations; with inotify and --pid=P, check process P
              at least once every N seconds

       -v, --verbose
              always output headers giving file names

       -z, --zero-terminated
              line delimiter is NUL, not newline

       --help display this help and exit

       --version
              output version information and exit

       NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB
       1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so
       on for T, P, E, Z, Y.  Binary prefixes can be used, too: KiB=K,
       MiB=M, and so on.

       With --follow (-f), tail defaults to following the file descriptor,
       which means that even if a tail'ed file is renamed, tail will
       continue to track its end.  This default behavior is not desirable
       when you really want to track the actual name of the file, not the
       file descriptor (e.g., log rotation).  Use --follow=name in that
       case.  That causes tail to track the named file in a way that
       accommodates renaming, removal and creation.
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector