Меню

Bash отключить вывод ошибок

Например, команда:

$ grep -lr "sample" .

помимо печати файлов, в которых содержится строка «sample», выводит ошибки, загромождающие вывод.

grep: <…>: Нет такого файла или каталога
grep: <…>: Нет такого файла или каталога

задан 26 ноя 2010 в 13:29

stanislav's user avatar

stanislavstanislav

34.1k25 золотых знаков95 серебряных знаков212 бронзовых знаков

Можно использовать, встроенные опции команды (согласно справке):

$ grep -lsr "sample" .

а можно перенаправить вывод ошибок в никуда:

$ grep -lr "sample" . 2>/dev/null

ответ дан 26 ноя 2010 в 18:15

Nicolas Chabanovsky's user avatar

Nicolas ChabanovskyNicolas Chabanovsky

50.5k80 золотых знаков257 серебряных знаков493 бронзовых знака

8.4.2. Подавление вывода сообщений об ошибках

Допустим, вы хотите найти запись пользователя louise в системном файле паролей:

$ grep louise /etc/passwd

louise:lxAL6GW9G.ZyY:501:501:Accounts Sect1С:/home/accts/louise:/bin/sh

He исключена возможность, что вы забудете, как называется этот файл. В таком случае воспользуйтесь следующей командой:

$ grep louise /etc/password

grep: /etc/password: No such file or directory

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

$ grep louise /etc/*

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

В подобной ситуации можно воспользоваться опцией -s, которая подавляет вывод сообщений об ошибках:

$ grep -a louise /etc/*

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

$ grep louise /etc/* 2> /dev/null

Эта команда направляет поток ошибок (2>) в системную корзину (устройство /dev/null). На жаргоне системных администраторов это устройство называется битодробилкой.

Читайте также

Уровни вывода сообщений ядра

Уровни вывода сообщений ядра
Главное отличие между функциями printk() и printf() — это возможность в первой указывать уровень вывода сообщений ядра (loglevel). Ядро использует уровень вывода сообщений для принятия решения о том, выводить сообщение на консоль или нет. Ядро выводит на

Отправка сообщений об ошибках

Отправка сообщений об ошибках
Если вы обнаружили ошибку, то наилучшим решением будет исправить ее, сгенерировать соответствующую заплату, оттестировать и отправить, как это будет рассказано в следующих разделах. Конечно, можно и просто сообщить об ошибке, чтобы

7.2 Сообщения об ошибках ICMP

7.2 Сообщения об ошибках ICMP
Бывают ситуации, приводящие к отбрасыванию (удалению из сети) датаграммы IP. Например, точка назначения может стать недоступной из-за обрыва связи. Или может завершиться время жизни датаграммы. Маршрутизатор не сможет переслать длинную

7.2.1 Типы сообщений об ошибках

7.2.1 Типы сообщений об ошибках
На рис. 7.3 показаны обобщенные сообщения, формируемые маршрутизатором и хостом назначения для отчета о возникшей проблеме. В таблице 7.1 перечислены формальные имена сообщений об ошибках ICMP.

Рис. 7.3. Типы сообщений об ошибках ICMPТаблица 7.1

Подавление линий заднего плана

Подавление линий заднего плана

Команда HIDE обеспечивает создание рисунка без скрытых линий. Сложные трехмерные модели часто оказываются перегруженными, что затрудняет их чтение и просмотр результатов выполнения какой-либо команды на объекте. Можно устранить эту

В.З. Стандартные функции вывода сообщений об ошибках

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

Отчет об ошибках

Отчет об ошибках
На вкладке Дополнительно в окне Свойства системы нажимаем кнопку Отчет об ошибках. Откроется одноименное окно Отчет об ошибках (рис. 4.5), в котором устанавливаем переключатель в положение Отключить отчет об ошибках и оставляем установленным флажок Но

Получение и пересылка сообщений. Создание ответных сообщений

Получение и пересылка сообщений. Создание ответных сообщений
Чтобы получить новую почту, выполните команду главного меню Сервис ? Отправить/Получить ? Доставить почту либо нажмите клавишу F9. Все полученные почтовые сообщения будут помещены в папку Входящие и помечены

Шаг 20 — Временные объекты. Неявные вызовы конструкторов и их подавление.

Шаг 20 — Временные объекты. Неявные вызовы конструкторов и их подавление.
Не удается углубиться в какую-либо тему. Приходится касаться по верхам, потом переключаться на что-то другое. С другой стороны, может это и правильно, часто достаточно только знать, что есть ТАКОЕ

Настройка вывода сообщений об ошибках с помощью ‹customErrors›

Настройка вывода сообщений об ошибках с помощью ‹customErrors›
Элемент ‹customErrors› может использоваться для автоматического перенаправления всех ошибок в пользовательский набор файлов *.htm. Это может оказаться полезным тогда, когда вы хотите построить более понятную для

Подавление линий заднего плана

Подавление линий заднего плана

Команда HIDE обеспечивает создание рисунка без скрытых линий. Сложные трехмерные модели часто оказываются перегруженными, что затрудняет их чтение и просмотр результатов выполнения какой-либо команды на объекте. Можно устранить эту

Сообщение об ошибках gbak

Сообщение об ошибках gbak
В табл. 38.3 описаны сообщения об ошибках, которые могут возникнуть в процессе копирования и восстановления, вместе с некоторыми советами, как поступать с этими ошибками.Таблица 38.3. Сообщения об ошибках gbak при копировании и восстановлении

Сообщение

Подавление линий заднего плана

Подавление линий заднего плана

Команда HIDE обеспечивает создание рисунка без скрытых линий . Сложные трехмерные модели часто оказываются перегруженными, что затрудняет их чтение и просмотр результатов выполнения какой-либо команды на объекте. Можно устранить эту

Подавление линий заднего плана

Подавление линий заднего плана

Команда HIDE обеспечивает создание рисунка без скрытых линий. Сложные трехмерные модели часто оказываются перегруженными, что затрудняет их чтение и просмотр результатов выполнения какой-либо команды на объекте. Можно устранить эту

Отчеты об ошибках

Отчеты об ошибках
В операционной системе Windows Vista реализован новый механизм отчетов об ошибках. Теперь ограничить и настроить его работу можно с помощью следующих параметров, расположенных в ветви реестра HKEY_CURRENT_USERSoftwarePoliciesMicrosoftWindowsWindows Error Reporting. Если не сказано иное,

I have a program that outputs to stdout and would like to silence that output in a Bash script while piping to a file.

For example, running the program will output:

% myprogram
% WELCOME TO MY PROGRAM
% Done.

I want the following script to not output anything to the terminal:

#!/bin/bash
myprogram > sample.s

codeforester's user avatar

codeforester

37.1k16 gold badges107 silver badges132 bronze badges

asked Feb 18, 2010 at 22:53

Sam's user avatar

3

If it outputs to stderr as well you’ll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

Kevin Ji's user avatar

Kevin Ji

10.4k4 gold badges39 silver badges58 bronze badges

answered Feb 18, 2010 at 22:58

John Kugelman's user avatar

John KugelmanJohn Kugelman

342k67 gold badges517 silver badges565 bronze badges

5

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

CTS_AE's user avatar

CTS_AE

11.9k8 gold badges56 silver badges60 bronze badges

answered Feb 18, 2010 at 23:27

Debugger's user avatar

DebuggerDebugger

8,87017 gold badges43 silver badges53 bronze badges

2

All output:

scriptname &>/dev/null

Portable:

scriptname >/dev/null 2>&1

Portable:

scriptname >/dev/null 2>/dev/null

For newer bash (no portable):

scriptname &>-

answered Aug 3, 2013 at 18:27

Eduardo Cuomo's user avatar

Eduardo CuomoEduardo Cuomo

17k6 gold badges110 silver badges92 bronze badges

2

If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative:

echo "hi" | grep "use this hack to hide the oputut :) "

answered Jul 14, 2016 at 7:52

Henry H.'s user avatar

Henry H.Henry H.

9018 silver badges11 bronze badges

1

If you want STDOUT and STDERR both [everything], then the simplest way is:

#!/bin/bash
myprogram >& sample.s

then run it like ./script, and you will get no output to your terminal. 🙂

the «>&» means STDERR and STDOUT. the & also works the same way with a pipe: ./script |& sed
that will send everything to sed

answered May 4, 2011 at 14:55

Matt's user avatar

MattMatt

2,6726 gold badges22 silver badges34 bronze badges

2

Try with:

myprogram &>/dev/null

to get no output

answered Dec 11, 2014 at 9:39

Swathi's user avatar

SwathiSwathi

2924 silver badges6 bronze badges

0

Useful variations:


  • Get only the STDERR in a file, while hiding any STDOUT even if the
    program to hide isn’t existing at all. (does not ever hang):

    stty -echo && ./programMightNotExist 2> errors.log && stty echo
    

  • Detach completely and silence everything, even killing the parent
    script won’t abort ./prog (Does behave just like nohup):

    ./prog </dev/null >/dev/null 2>&1 &
    

  • nohup can be used as well to fully detach, as follow:

    nohup ./prog &
    

    A log file nohup.out will be created aside of the script, use tail -f nohup.out to read it.

answered Oct 30, 2019 at 5:44

NVRM's user avatar

NVRMNVRM

10.5k1 gold badge82 silver badges85 bronze badges

Note: This answer is related to the question «How to turn off echo while executing a shell script Linux» which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don’t want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won’t see what he/she types in from then on. To turn echo on run:

stty echo

answered Aug 22, 2018 at 19:34

Berni's user avatar

For output only on error:

so [command]

Logo

answered May 25, 2020 at 3:12

Alberto Salvia Novella's user avatar

I have a program that outputs to stdout and would like to silence that output in a Bash script while piping to a file.

For example, running the program will output:

% myprogram
% WELCOME TO MY PROGRAM
% Done.

I want the following script to not output anything to the terminal:

#!/bin/bash
myprogram > sample.s

codeforester's user avatar

codeforester

37.1k16 gold badges107 silver badges132 bronze badges

asked Feb 18, 2010 at 22:53

Sam's user avatar

3

If it outputs to stderr as well you’ll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

Kevin Ji's user avatar

Kevin Ji

10.4k4 gold badges39 silver badges58 bronze badges

answered Feb 18, 2010 at 22:58

John Kugelman's user avatar

John KugelmanJohn Kugelman

342k67 gold badges517 silver badges565 bronze badges

5

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

CTS_AE's user avatar

CTS_AE

11.9k8 gold badges56 silver badges60 bronze badges

answered Feb 18, 2010 at 23:27

Debugger's user avatar

DebuggerDebugger

8,87017 gold badges43 silver badges53 bronze badges

2

All output:

scriptname &>/dev/null

Portable:

scriptname >/dev/null 2>&1

Portable:

scriptname >/dev/null 2>/dev/null

For newer bash (no portable):

scriptname &>-

answered Aug 3, 2013 at 18:27

Eduardo Cuomo's user avatar

Eduardo CuomoEduardo Cuomo

17k6 gold badges110 silver badges92 bronze badges

2

If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative:

echo "hi" | grep "use this hack to hide the oputut :) "

answered Jul 14, 2016 at 7:52

Henry H.'s user avatar

Henry H.Henry H.

9018 silver badges11 bronze badges

1

If you want STDOUT and STDERR both [everything], then the simplest way is:

#!/bin/bash
myprogram >& sample.s

then run it like ./script, and you will get no output to your terminal. 🙂

the «>&» means STDERR and STDOUT. the & also works the same way with a pipe: ./script |& sed
that will send everything to sed

answered May 4, 2011 at 14:55

Matt's user avatar

MattMatt

2,6726 gold badges22 silver badges34 bronze badges

2

Try with:

myprogram &>/dev/null

to get no output

answered Dec 11, 2014 at 9:39

Swathi's user avatar

SwathiSwathi

2924 silver badges6 bronze badges

0

Useful variations:


  • Get only the STDERR in a file, while hiding any STDOUT even if the
    program to hide isn’t existing at all. (does not ever hang):

    stty -echo && ./programMightNotExist 2> errors.log && stty echo
    

  • Detach completely and silence everything, even killing the parent
    script won’t abort ./prog (Does behave just like nohup):

    ./prog </dev/null >/dev/null 2>&1 &
    

  • nohup can be used as well to fully detach, as follow:

    nohup ./prog &
    

    A log file nohup.out will be created aside of the script, use tail -f nohup.out to read it.

answered Oct 30, 2019 at 5:44

NVRM's user avatar

NVRMNVRM

10.5k1 gold badge82 silver badges85 bronze badges

Note: This answer is related to the question «How to turn off echo while executing a shell script Linux» which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don’t want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won’t see what he/she types in from then on. To turn echo on run:

stty echo

answered Aug 22, 2018 at 19:34

Berni's user avatar

For output only on error:

so [command]

Logo

answered May 25, 2020 at 3:12

Alberto Salvia Novella's user avatar

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Bash завершить скрипт ошибкой
  • Bash завершение скрипта при ошибке