Dev null file linux

What does /dev/null mean in a shell script? [duplicate]

I’ve started learning bash scripting by using this guide: http://www.tldp.org/LDP/abs/abs-guide.pdf However I got stuck at the first script:

cd /var/log cat /dev/null > messages cat /dev/null > wtmp echo "Log files cleaned up." 

What do lines 2 and 3 do in Ubuntu (I understand cat )? Is it only for other Linux distributions? After running this script as root, the output I get is Log files cleaned up. But /var/log still contains all the files.

I see 1 problem with this: the 2nd and 3rd line ONLY work with running as root. Otherwise you need sudo in front of it.

5 Answers 5

Assuming the commands succeeded, /var/log/messages and /var/log/wtmp still exist but are now blank.

Shell Redirection

> is a redirection operator, implemented by the shell. Its syntax is:

  • file may also be a device node.
  • If file doesn’t exist, it is created as a regular file.
  • If file already exists as a regular file and is non-empty, it is overwritten. This is typically the case in the commands you ran, where you redirected the output of cat /dev/null to messages and wtmp .
  • If file already exists as a symbolic link, the link’s target is used.
  • If file already exists as a directory, you’ll get an error like bash: file: Is a directory .

(Of course, these operations may fail for other reasons, such as lack of permissions or a filesystem error.)

The >> redirection operator is similar, but it appends to the end of non-empty regular files instead of overwriting their contents. (Another redirection operator is < . command < file uses file as command ‘s standard input.)

The null Device

/dev/null is a simple device (implemented in software and not corresponding to any hardware device on the system).

  • /dev/null looks empty when you read from it.
  • Writing to /dev/null does nothing: data written to this device simply «disappear.»

Often a command’s standard output is silenced by redirecting it to /dev/null , and this is perhaps the null device’s commonest use in shell scripting:

You’re using /dev/null differently. cat /dev/null outputs the «contents» of /dev/null , which is to say its output is blank. > messages (or > wtmp ) causes this blank output to be redirected to the file on the right side of the > operator.

Since messages and wtmp are regular files (rather than, for example, device nodes), they are turned into blank files (i.e., emptied).

You could use any command that does nothing and produces no output, to the left of > .

An alternative way to clear these files would be to run:

echo -n > messages echo -n > wtmp 

The -n flag is required, or echo writes a newline character.

(This always works in bash . And I believe the default sh in every GNU/Linux distribution and other Unix-like system popularly used today supports the -n flag in its echo builtin. But jlliagre is right that echo -n should be avoided for a truly portable shell script, as it’s not required to work. Maybe that’s why the guide you’re using teaches the cat /dev/null way instead.)

Читайте также:  Linux перейти из root

The echo -n way is equivalent in its effects but arguably is a better solution, in that it’s simpler.
cat /dev/null > file opens three «files»:

In contrast, echo -n > file opens only file ( echo is a shell builtin).

Although this should be expected to improve performance, that’s not the benefit—not when just running a couple of these commands by hand, anyway. Instead, the benefit is that it’s easier to understand what’s going on.

Redirection and the trivial (blank/empty) command.

As jlliagre has pointed out (see also jlliagre’s answer), this can be shortened further by simply omitting the command on the left of > altogether. While you cannot omit the right side of a > or >> expression, the blank command is valid (it’s the command you’re running when you just press Enter on an empty prompt), and in omitting the left side you’re just redirecting the output of that command.

  • Note that this output does not contain a newline. When you press Enter on a command prompt—whether or not you’ve typed anything—the shell (running interactively) prints a newline before running the command issued. This newline is not part of the command’s output.

Redirecting from the blank command (instead of from cat /dev/null or echo -n ) looks like:

Источник

How to Create /dev/null

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

In the shell scripting world /dev/null is a fundamental concept. Its accidental deletion might wreak havoc on the system because many system processes rely on it. So, knowing what /dev/null is and how to work with it is essential for any Linux developer.

As we’ll see in this tutorial, issues caused by a missing /dev/null are temporary and can be easily fixed.

2. What Is /dev/null?

In Linux systems, devices are files stored in the /dev directory. These files can represent both physical and virtual devices. /dev/null is a virtual null device used to discard any output redirected to it.

There are two types of output streams to redirect, standard output (stdout) and standard error (stderr). Each stream has a numerical descriptor, 1 for stdout and 2 for stderr.

To suppress one of these streams, we simply redirect it to /dev/null using the descriptor and > redirect operator:

When we omit the descriptor, it’s assumed to be stdout for an output type stream.

Читайте также:  Linux не могу запустить бинарный файл

In order to suppress both streams in one command, we can write both in one line:

$ command > /dev/null 2> /dev/null 

A shorter option is to redirect stdout to /dev/null and then redirect stderr to stdout:

The &1 notation means the destination is a file descriptor, not a file named 1.

Additionally, the above can be written much shorter using &>:

In this shorthand, &> is the semantic equivalent for both redirections.

3. Inspecting the Properties of /dev/null

Now, let’s try to echo some text and redirect the output to /dev/null. If we try to read it, it’ll give EOF:

$ echo "Hello world!" > /dev/null $ cat /dev/null 

Here, we’ll get no output. The file is completely empty.

Now, let’s see what properties /dev/null has:

$ ls -l /dev/null crw-rw-rw- 1 root root 1, 3 May 23 23:56 /dev/null 
$ stat /dev/null File: /dev/null Size: 0 Blocks: 0 IO Block: 4096 character special file Device: 5h/5d Inode: 5 Links: 1 Device type: 1,3 Access: (0666/crw-rw-rw-) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2023-05-23 23:56:28.815999926 -0700 Modify: 2023-05-23 23:56:28.815999926 -0700 Change: 2023-05-23 23:56:28.815999926 -0700 Birth: - 

As we see in the results, the file size is 0 and it belongs to the root user. All categories, including the owner, have only read and write permissions. Also, the device type numbers 1 and 3 are major and minor device categories specific to /dev/null.

Another noteworthy piece of information is the special type. Here, c denotes a character device, also called a character special file. These devices behave like pipes and allow direct unbuffered access to the device. Furthermore, they handle each character individually, hence the name.

4. Experimenting with Deleting /dev/null

First, we need to delete /dev/null to demonstrate recovery. Note, however, this tutorial seeks to help in case it is already deleted. There’s absolutely no need to follow along and actually delete /dev/null unless it’s a safe experiment in a VM.

Since the file belongs to root, it won’t be possible for a random user with no such access to accidentally delete it. Therefore, to delete, we run the rm command as root:

Anything strange can happen after this step. After all, /dev/null is essential for the system, and having it removed isn’t a healthy state.

On the Ubuntu 20.04 VM where this experiment was held, the system froze and the screen went black after trying to open Settings from the right-click menu on the Desktop. On another occasion, after the user was logged out due to inactivity, it was no longer possible to log in. Thus, we have only one choice in such cases: force reboot.

5. Creating /dev/null

Luckily for us, the system recovers /dev/null after reboot. But this isn’t an optimal solution, since any unsaved work will be gone. Therefore, immediately after accidental deletion and before anything strange happens, we need to recover /dev/null manually.

For that, we’ll use the mknod command to create a character special file. We have to specify the original device types 1 and 3:

After the file is created, we need to set the correct permissions for all categories:

In fact, the same can also be done with just mknod and the —mode, or short -m, option:

$ mknod -m 0666 /dev/null c 1 3 

Additionally, it’s possible for the processes redirecting to /dev/null to unknowingly recreate it as a regular file. In case that happens, we’ll need to create the real one with a different name, such as /dev/null-new, then force move over to replace the fake one:

Читайте также:  What is linux mint cinnamon and mate

A reboot afterward might also be necessary.

6. Conclusion

In this article, we’ve seen why /dev/null is important and how to create it.

With this information, we are fully equipped to recover the system in case /dev/null is accidentally deleted.

In the worst case, a simple reboot will fix everything.

Источник

Как работает файл /dev/null в Linux

/dev/null в Linux — это файл нулевого устройства. Он удаляет все записанное в него и возвращает при чтении EOF ( End of File) .

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

Давайте посмотрим, что это значит на практике и что мы можем сделать с этим файлом.

Свойства /dev/null

Следующая команда cat вернет символ конца файла (EOF), если вы попытаетесь прочитать его с ее помощью.

Валидность файла можно проверить с помощью:

 File: /dev/null Size: 0 Blocks: 0 IO Block: 4096 character special file Device: 6h/6d Inode: 5 Links: 1 Device type: 1,3 Access: (0666/crw-rw-rw-) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2020-02-04 13:00:43.112464814 +0530 Modify: 2020-02-04 13:00:43.112464814 +0530 Change: 2020-02-04 13:00:43.112464814 +0530

Этот вывод показывает, что данный файл имеет размер 0 байт, для него выделено ноль блоков. Права доступа к файлу установлены таким образом, что любой может читать/записывать его, но никто не может его выполнять.

Поскольку это не исполняемый файл, мы не можем использовать конвейер — оператор | для перенаправления на /dev/null. Единственный способ — использовать перенаправления файлов (>, >> или

На приведенной ниже диаграмме показано, что /dev/null действительно является валидным файлом.

Давайте теперь рассмотрим некоторые распространенные варианты использования /dev/null.

Перенаправление на /dev/null в Linux

Мы можем отказаться от любого вывода скрипта, который мы используем, перенаправив его на /dev/null.

Для примера попробуйте сбросить сообщения команды echo , используя этот файл.

echo ‘Hello from JournalDev’ > /dev/null

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

Давайте попробуем запустить неправильную команду и направить ее вывод в /dev/null .

cat —INCORRECT_OPTION > /dev/null

cat: unrecognized option ‘—INCORRECT’
Try ‘cat —help’ for more information.

Почему это происходит? Это связано с тем, что сообщения об ошибках поступают из stderr, а мы перенаправляем только вывод из stdout.

Однако мы также должны учитывать stderr.

Сброс сообщений об ошибках

Давайте перенаправим stderr в /dev/null вместе с stdout. Для этого мы можем использовать файловый дескриптор stderr(=2).

cat —INCORRECT_OPTION > /dev/null 2>/dev/null

Это даст нам желаемый результат.

Есть и другой способ сделать то же самое: сначала перенаправить stderr на stdout, а затем — stdout на /dev/null.

Синтаксис для этого выглядит так:

Обратите внимание на 2>&1 в конце. Мы перенаправляем stderr(2) на stdout(1). С помощью &1 мы сообщаем оболочке, что конечный файл на самом деле является файловым дескриптором.

Поэтому если мы используем 2>1 (без амперсанда), мы просто перенаправим stderr в файл по имени 1 — а это не то, что нам нужно.

Источник

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