Linux stderr to dev null

♾️ Что такое /dev/null в Linux?

С технической точки зрения «/dev/null» является файлом виртуального устройства.

Что касается программ, то они обрабатываются как реальные файлы.

Утилиты могут запрашивать данные из такого рода источников, а операционная система передает им данные.

Но вместо чтения с диска операционная система генерирует эти данные динамически.

Примером такого файла является «/dev/zero».

В этом случае, однако, вы будете записывать в файл устройства

Все, что вы пишете в «/dev/null», отбрасывается, забывается и выбрасывается в пустоту.

Чтобы понять, почему это полезно, вы должны сначала иметь представление о стандартном выводе и стандартной ошибке в операционных системах Linux или * nix.

stdout и stder

Утилита командной строки может генерировать два типа вывода.

Стандартный вывод отправляется на stdout.

Ошибки отправляются в stderr.

По умолчанию stdout и stderr связаны с окном вашего терминала (или консолью).

Это означает, что все, что отправлено на stdout и stderr, обычно отображается на вашем экране.

Но с помощью перенаправления оболочки вы можете изменить это поведение.

Например, вы можете перенаправить стандартный вывод в файл.

Таким образом, вместо отображения вывода на экране, он будет сохранен в файл, который вы сможете прочитать позже, или вы можете перенаправить стандартный вывод на физическое устройство, например, на цифровой светодиод или ЖК-дисплей.

  • С 2> вы перенаправляете стандартные сообщения об ошибках. Пример: 2> /dev/null или 2> /home/user/error.log.
  • С 1> вы перенаправляете стандартный вывод.
  • С &> вы перенаправляете как стандартную ошибку, так и стандартный вывод.

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

Поскольку существует два типа вывода: стандартный вывод и стандартная ошибка, первый вариант использования – отфильтровать один тип или другой.

Это легче понять на практическом примере.

Допустим, вы ищете строку в «/sys», чтобы найти файлы, которые относятся к настройкам питания.

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

Это приведет к множеству ошибок «Отказано в доступе».

Это затрудняет поиск результатов, которые вы ищете.

Поскольку ошибки «Permission denied» являются частью stderr, вы можете перенаправить их на «/dev/null».

Как видите, это гораздо легче читать.

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

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

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

Вы можете перенаправить как stdout, так и stderr в два разных места.

В этом случае сообщения стандартного вывода вообще не будут отображаться, а сообщения об ошибках будут сохраняться в файле «error.log».

Перенаправить весь вывод в /dev/null

Иногда полезно избавиться от всего вывода.

Есть два способа сделать это.

Читайте также:  Как задать том жесткому диску windows 10

Строка > /dev/null означает «отправить stdout в /dev/null», а вторая часть, 2>&1, означает отправить stderr в stdout.

В этом случае вы должны ссылаться на стандартный вывод как «&1» вместо простого «1.».

Запись «2>1» просто перенаправит стандартный вывод в файл с именем «1».

Здесь важно отметить, что порядок важен.

Если вы измените параметры перенаправления следующим образом:

это не будет работать как задумано.

Это потому, что, как только 2>&1 интерпретируется, stderr отправляется на стандартный вывод и отображается на экране.

Затем stdout подавляется при отправке в «/dev/null».

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

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

В этом случае &>/dev/null эквивалентно сообщению «перенаправить как stdout, так и stderr в это местоположение».

Другие примеры, где это может быть полезно для перенаправления в /dev/null

Скажем, вы хотите увидеть, как быстро ваш диск может читать последовательные данные.

Источник

Unix and Linux: Redirect Error Output To null Command

  1. stdin – 0 – Standard Input (usually keyboard or file)
  2. stdout – 1 – Standard Output (usually screen)
  3. stderr – 2 – Standard Error (usually screen)

[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

[/donotprint]

What is a null (/dev/null) file in a Linux or Unix-like systems?

/dev/null is nothing but a special file that discards all data written to it. The length of the null device is always zero. In this example, first, send output of date command to the screen and later to the /dev/null i.e. discards date command output:

Syntax: Standard Error (stderr -2 no) to a file or /dev/null

The syntax is as follows:

In this example, send output of find command to /dev/null:
$ find /etc -type f -name ‘*’ 2>/dev/null
The following example will cause the stderr ouput of a program to be written to a file called errors.txt:
$ find /etc/ -type f -name «*» 2> errors.txt

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Linux and Unix redirect all output and error to file

If you want both stderr and stdout in same file, try:

Use cat command to display log.txt on screen:
cat log.txt

See man pages for more information – ksh(1).

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Your command will send output to both screen and file.

Источник

BASH Shell Redirect Output and Errors To /dev/null

H ow do I redirect output and errors to /dev/null under bash / sh shell scripting? How do I redirect the output of stderr to stdout, and then redirect this combined output to /dev/null device? In Unix, how do I redirect error messages to /dev/null?

You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2).

Tutorial details
Difficulty level Easy
Root privileges No
Requirements bash/ksh
Est. reading time 1m

So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.

Syntax to redirect error and output messages to /dev/null

The syntax discussed below works with Bourne-like shells, such as sh, ksh, and bash:

You can also use the same syntax for all your cronjobs to avoid emails and output / error messages:
@hourly /scripts/backup/nas.backup >/dev/null 2>&1
OR
@hourly /scripts/backup/nas.backup &>/dev/null

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Redirect both standard error and standard out messages to a log file

You can always redirect both standard error (stdin) and standard out (stdout) text to an output file or a log file by typing the following command:

Want to close stdout and stderr for the command being executed on a Linux/Unix/BSD/OSX bash shell?

Try the following syntax:

See man pages: ksh(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Another way to do it:

Or you can close stdout and stderr for the command being executed:

Remember to add an additional & at the end of the statement to run the command in the background. Thank you Giuseppe for the tip.

What do you mean by “close stdout and stderr” ?

Thanks! I was searching how resolve this problem, and your solution work perfect for me!

need a command in my bash script to remove some (not all) of the contents of directory2.
The script does NOT run as root, which works because it removes the correct files but not the root-level stuff in directory2 (that I don’t want to remove).
Problem is users get confused by the “permission denied” msgs output by the “rm”. So…
I tried to redirect the stderror & stdout to /dev/null this way:
rm * /directory1/directory2/ > 2&>1 /dev/null
kept changing /dev/null form a special file & other users need crw-rw-rw-
Will the recommended approaches allow me to redirect to /dev/null without messing it up for others?

You could use find instead to filter out the files you don’t want to delete, or only delete files matching a patter:

Delete all files except those with “attachments” in the name:
# find . ! -name ‘*attachments*’ -exec rm -v <> \;

Delete all files with “attachments” in the name:
# find . -name ‘*attachments*’ -exec rm -v <> \;

Find is very versitile, it’s pretty cool what you can acheive with find.

how does one redirect output from text file processing to a script file that uses the command line variable $1.

file iplist has a long list of IP’s on the network and i need to send this to a script that creates a file with the ping info.

script says: ping $1 > $1
Please assist if possible

How reliable, if that’s the word I’m looking for, is ending a particular command in a script with a redirect like “2>/dev/null” ? What have folks’ experiences been with the different commands and bash/sh versions when trying it this way?

I know it’s not recommended, but for someone like myself, with scripts they either run daily or don’t run for months and then go through a spate of executing them two and three times a day (only to go back to seldom running them until the next time it happens), it would be very convenient and not too too anxiety-producing to run a script and know that whatever passable or critical errors it comes up with are being suppressed.

I’m much more inclined to put up with circumstances after the fact, and I seldom write anything that’s too destructive (on the system or OS/hardware install and performance level, at any rate) for a little error like Exiv2 complaining about some JPG file’s Photoshop IFD entry being out of bounds.

Источник

Читайте также:  Zsh для windows 10
Оцените статью