Bash error dev null

We run daily Selenium tests to test our website and extensions. I wrote a script (according to this question) to count the number of passed and failed tests. Here is the script: #!/bin/bash today...

We run daily Selenium tests to test our website and extensions. I wrote a script (according to this question) to count the number of passed and failed tests. Here is the script:

#!/bin/bash

today=`TZ='Asia/Tel_Aviv' date +"%Y-%m-%d"`
yesterday=`TZ='Asia/Tel_Aviv' date +"%Y-%m-%d" -d "yesterday"`

...

print_test_results()
{
    declare -i passed_tests=0
    declare -i failed_tests=0
    declare -i total_tests=0
    log_suffix="_${file_name}.log"
    yesterday_logs="${log_prefix}${yesterday}_[1,2]*${log_suffix}"
    today_logs="${log_prefix}${today}_0*${log_suffix}"
    for temp_file_name in $yesterday_logs $today_logs ; do
        total_tests+=1
        if grep -q FAILED "$temp_file_name" ; then
            failed_tests+=1
        elif grep -q OK "$temp_file_name" ; then
            passed_tests+=1
        else
            failed_tests+=1
        fi
    done
    echo "<tr>"
    echo "<td>$test_name - $today</td>"
    if [ $passed_tests = "0" ]; then
        echo "<td>$passed_tests passed</td>"
        echo "<td><span style="color: red;">$failed_tests failed</span></td>"
    else
        echo "<td><span style="color: green;">$passed_tests passed</span></td>"
        echo "<td>$failed_tests failed</td>"
    fi
    echo "<td>$total_tests tests total</td>"
    echo "</tr>"
}

file_name="chrome_gmail_1_with_extension_test"
test_name="Chrome Gmail 1 With Extension Test"
print_test_results

...

But the problem is, if the files are not there (in $yesterday_logs $today_logs), I get error messages. How do I redirect these error messages to /dev/null? I want to redirect them to /dev/null from the script, and not from the line calling the script — I want this script to never show error messages about files which don’t exist.

Community's user avatar

asked Aug 9, 2015 at 7:01

Uri's user avatar

1

Just for the record:

In general, to suppress error messages in bash, use command 2>/dev/null. So in your case you should use grep -q OK 2>/dev/null.

But as your case also shows (from what I read in the comments) this is a risky thing to do, as it cloaks errors you might have in your code. «I want this script to never print error messages» should only be said when one knows all possible error cases which could possibly occur.

answered Aug 9, 2015 at 15:13

Alfe's user avatar

AlfeAlfe

54.6k19 gold badges101 silver badges157 bronze badges

7

Inside your script you can place this line at start:

shopt -s nullglob

This will not match anything if your glob pattern doesn’t find any matching file. Otherwise whole glob pattern is returned when you use something like:

for temp_file_name in $yesterday_logs $today_logs; do ... done

answered Aug 9, 2015 at 7:06

anubhava's user avatar

anubhavaanubhava

748k64 gold badges550 silver badges622 bronze badges

1

Eventually I changed this line to:

for temp_file_name in `ls $yesterday_logs $today_logs 2>/dev/null` ; do
    total_tests+=1
    if grep -q FAILED "$temp_file_name" ; then
        failed_tests+=1
    elif grep -q OK "$temp_file_name" ; then
        passed_tests+=1
    else
        failed_tests+=1
    fi
done

Then only the ls errors are directed to /dev/null.

answered Aug 30, 2015 at 6:45

Uri's user avatar

UriUri

2,7918 gold badges40 silver badges84 bronze badges

1

Содержание

  1. Shell Redirect Output And Errors To The Null Device In Bash
  2. Overview
  3. Concepts
  4. File descriptors
  5. Null device
  6. Redirect to the null device.
  7. Examples
  8. Summary
  9. Что такое /dev/null и как его использовать в Bash
  10. Предварительно
  11. Использование /dev/null
  12. Перенаправление вывода в /dev/null
  13. Перенаправить весь вывод в /dev/null
  14. Другие примеры
  15. How to Redirect Output to /dev/null in Linux
  16. What does ‘1>/dev/null’ mean?
  17. ♾️ Что такое /dev/null в Linux?
  18. stdout и stder
  19. Используйте /dev/null, чтобы избавиться от вывода, который вам не нужен
  20. Перенаправить весь вывод в /dev/null
  21. Другие примеры, где это может быть полезно для перенаправления в /dev/null

Shell Redirect Output And Errors To The Null Device In Bash

How to redirect output and errors to /dev/null in Bash

Overview

In shell scripting, you often want to avoid printing error messages to the console or discard any possible output the script could generate. Capturing program output can be done with I/O Redirection in Linux.

Concepts

In Linux, everything is a file, even data streams and devices are treated like ordinary files.

There are always three default files open:

stdin the keyboard stdout the screen stderr error messages output to the screen

Output from these files can be captured and sent as input to another file, command, program or script. This is called redirection.

How do you choose what file to handle? With file descriptors.

File descriptors

A file descriptor is simply a number that the operating system assigns to an open file to keep track of it. Consider it a simplified type of file pointer. It is analogous to a file handle in C.

Kowing the file descriptors of each file, we can select with which one we want to work and process redirection between them.

The file descriptors for our open files are:

Then we can use M>N in each command to redirect the file descriptor M to N:

  • M: file descriptor, which defaults to 1, if not explicitly set.

N can be:

  • N: filename,
  • &N: another file descriptor

Null device

Linux has a special device file that discards all data written to it. In Linux this device is /dev/null.

Redirect to the null device.

The way to discard commands output and error messages is to redirect them to the null device.

This can be done explicitely redirecting both output and/or errors in many ways:

Redirect stdout to the null device:

Redirect stderr to the null device

Redirect both stdout and stderr to the null device

Redirect stderr to the same file of stdout

Examples

Let’s see a simple example with the ls command:

stdout file descriptor isn’t present so it defaults to 1, any error would be echoed to the screen.

we only redirect stdout but we still see the error generated by the command.

we produce an error with ls but redirects the error output to the null device, so we don’t see any output in the screen.

we avoid outputting errors and the standard command output.

Summary

Understanding file descriptors is key to handle commands output and errors.

This is a common practice to avoid outputting anything in cronjobs where the output would be sent to the users email.

Additionally, it is very useful to work with bash redirection not only to the null device.

Источник

Что такое /dev/null и как его использовать в Bash

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

Одним из таких примеров является /dev/null . Это специальный файл, который присутствует в каждой системе Linux. Однако, в отличие от большинства других виртуальных файлов, вместо чтения он используется для записи. Все, что вы запишете в /dev/null , будет отброшено, забыто в пустоте. В системе UNIX он известен как нулевое устройство.

Зачем вам выбрасывать что-то в пустоту? Давайте посмотрим, что такое /dev/null и как он используется.

Предварительно

Прежде чем углубиться в использование /dev/null , мы должны иметь четкое представление о потоке данных stdout и stderr . Ознакомьтесь с этим коротким руководством по stdin, stderr и stdout.

Давайте сделаем небольшое уточнение. При запуске любой утилиты командной строки она генерирует два вывода. Вывод идет на stdout , а ошибка (если она возникла) — на stderr . По умолчанию оба этих потока данных связаны с терминалом.

Например, следующая команда выведет строку, заключенную в двойные кавычки. Здесь вывод сохраняется в stdout .

Следующая команда покажет нам статус выхода ранее запущенной команды.

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

Теперь нам нужно разобраться в файловом дескрипторе. В экосистеме UNIX это целочисленные значения, присвоенные файлу. И stdout (дескриптор файла = 1), и stderr (дескриптор файла = 2) имеют определенный дескриптор файла. Используя дескриптор файла (1 и 2), мы можем перенаправить stdout и stderr в другие файлы.

Для начала, следующий пример перенаправит stdout команды echo в текстовый файл. Здесь мы не указали дескриптор файла. Если он не указан, bash будет использовать stdout по умолчанию.

Следующая команда перенаправит stderr в текстовый файл.

Использование /dev/null

Перенаправление вывода в /dev/null

Теперь мы готовы узнать, как использовать /dev/null . Сначала давайте проверим, как фильтровать обычный вывод и ошибки. В следующей команде grep попытается найти строку (hello, в данном случае) в каталоге «/sys».

Однако это вызовет множество ошибок, поскольку без привилегий root grep не может получить доступ к ряду файлов. В этом случае он выдаст ошибку «Permission denied». Теперь, используя перенаправление, мы можем получить более четкий результат.

Вывод выглядит намного лучше, верно? Ничего! В этом случае у grep нет доступа ко многим файлам, а в тех, что есть, нет строки «hello».

В следующем примере мы будем пинговать Google.

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

Здесь содержимое stdout сбрасывается в /dev/null , оставляя только ошибки.

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

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

Давайте немного разобьем эту команду. Сначала мы сбрасываем весь stdout в /dev/null . Затем, во второй части, мы говорим bash отправить stderr в stdout . В этом примере выводить нечего. Однако, если вы запутались, вы всегда можете проверить, успешно ли выполнилась команда.

Значение равно 2, потому что команда выдала много ошибок.

Если вы склонны забывать файловый дескриптор stdout и stderr, следующая команда подойдет как нельзя лучше. Это более обобщенный формат предыдущей команды. И stdout, и stderr будут перенаправлены в /dev/null.

Другие примеры

Это интересный пример. Знаете инструмент dd ? Это мощный инструмент для преобразования и копирования файлов. Узнайте больше о dd . Используя dd , мы можем проверить скорость последовательного чтения вашего диска. Конечно, это не точное измерение. Однако для быстрого теста это довольно полезно.

Здесь я использовал Ubuntu 18.04.4 ISO в качестве большого файла.

Аналогичным образом вы также можете проверить скорость загрузки вашего интернет-соединения.

Надеемся, у вас есть четкое понимание того, что такое файл /dev/null. Это специальное устройство, которое при записи в него отбрасывает, а при чтении из него считывает null. Истинный потенциал этой интересной возможности заключается в интересных bash-скриптах.

Источник

How to Redirect Output to /dev/null in Linux

In Linux, programs are very commonly accessed using the command line and the output, as such, is displayed on the terminal screen. The output consists of two parts: STDOUT (Standard Output), which contains information logs and success messages, and STDERR (Standard Error), which contains error messages.

Many times, the output contains a lot of information that is not relevant, and which unnecessarily utilizes system resources. In the case of complex automation scripts especially, where there are a lot of programs being run one after the other, the displayed log is huge.

In such cases, we can make use of the pseudo-device file ‘/dev/null‘ to redirect the output. When the output is redirected to /dev/null, it is immediately discarded, and thus, no resource utilization takes place.

Let’s see how to redirect output to /dev/null in Linux.

Let us take an example of the mv command trying to move two files to a particular directory, where one file is moved successfully (displays STDOUT) and the other gives an error while moving (displays STDERR).

Move Multiple Files in Linux

Note: The ‘-v’ argument to mv displays the success log when a file is moved. Without the flag, nothing is printed to STDOUT.

Now, to redirect only the STDOUT to /dev/null, i.e. to discard the standard output, use the following:

Redirect STDOUT to /dev/null

What does ‘1>/dev/null’ mean?

Here ‘1’ indicates STDOUT, which is a standard integer assigned by Linux for the same. The operator ‘>’ , called a redirection operator, writes data to a file. The file specified in this case is /dev/null. Hence, the data is ultimately discarded.

If any other file were given instead of /dev/null, the standard output would have been written to that file.

Similarly, to redirect only the STDERR to /dev/null, use the integer ‘2’ instead of ‘1’ . The integer ‘2’ stands for standard error.

Redirect STDERR Output to /dev/null

As you can see, the standard error is not displayed on the terminal now as it is discarded in /dev/null.

Finally, to discard both STDOUT and STDERR at the same time, use the following:

Redirect STDOUT and STDERR output to /dev/null

The ampersand character (‘&’) denotes that both the standard output and standard error has to be redirected to /dev/null and discarded. Hence, in the last screenshot, we do not see any output printed on the screen at all.

Conclusion

In this article, we have seen how to redirect output to /dev/null. The same can be used in either command or in complex Bash scripts which generate a heavy amount of log. In case if the script needs debugging, or has to be tested; in such cases, the log is required to view and analyze the errors properly.

However in cases when the output is already known and anticipated, it can be discarded with /dev/null. If you have any questions or feedback, let us know in the comments below!

Источник

♾️ Что такое /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

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

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

Строка > /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

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

Источник

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

Одним из таких примеров является /dev/null. Это специальный файл, который присутствует в каждой системе Linux. Однако, в отличие от большинства других виртуальных файлов, вместо чтения он используется для записи. Все, что вы запишете в /dev/null, будет отброшено, забыто в пустоте. В системе UNIX он известен как нулевое устройство.

Зачем вам выбрасывать что-то в пустоту? Давайте посмотрим, что такое /dev/null и как он используется.

Предварительно

Прежде чем углубиться в использование /dev/null, мы должны иметь четкое представление о потоке данных stdout и stderr. Ознакомьтесь с этим коротким руководством по stdin, stderr и stdout.

Давайте сделаем небольшое уточнение. При запуске любой утилиты командной строки она генерирует два вывода. Вывод идет на stdout, а ошибка (если она возникла) — на stderr. По умолчанию оба этих потока данных связаны с терминалом.

Например, следующая команда выведет строку, заключенную в двойные кавычки. Здесь вывод сохраняется в stdout.

$ echo "Hello World"

Следующая команда покажет нам статус выхода ранее запущенной команды.

$ echo $?

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

$ adfadsf
$ echo $?

Теперь нам нужно разобраться в файловом дескрипторе. В экосистеме UNIX это целочисленные значения, присвоенные файлу. И stdout (дескриптор файла = 1), и stderr (дескриптор файла = 2) имеют определенный дескриптор файла. Используя дескриптор файла (1 и 2), мы можем перенаправить stdout и stderr в другие файлы.

Для начала, следующий пример перенаправит stdout команды echo в текстовый файл. Здесь мы не указали дескриптор файла. Если он не указан, bash будет использовать stdout по умолчанию.

$ echo "Hello World" > log.txt

Следующая команда перенаправит stderr в текстовый файл.

$ asdfadsa 2> error.txt

Использование /dev/null

Перенаправление вывода в /dev/null

Теперь мы готовы узнать, как использовать /dev/null. Сначала давайте проверим, как фильтровать обычный вывод и ошибки. В следующей команде grep попытается найти строку (hello, в данном случае) в каталоге «/sys».

$ grep -r hello /sys/

Однако это вызовет множество ошибок, поскольку без привилегий root grep не может получить доступ к ряду файлов. В этом случае он выдаст ошибку «Permission denied». Теперь, используя перенаправление, мы можем получить более четкий результат.

$ grep -r hello /sys/ 2> /dev/null

Вывод выглядит намного лучше, верно? Ничего! В этом случае у grep нет доступа ко многим файлам, а в тех, что есть, нет строки «hello».

В следующем примере мы будем пинговать Google.

$ ping google.com

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

$ ping google.com 1> /dev/null

Здесь содержимое stdout сбрасывается в /dev/null, оставляя только ошибки.

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

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

$ grep -r hello /sys/ > /dev/null 2>&1

Давайте немного разобьем эту команду. Сначала мы сбрасываем весь stdout в /dev/null. Затем, во второй части, мы говорим bash отправить stderr в stdout. В этом примере выводить нечего. Однако, если вы запутались, вы всегда можете проверить, успешно ли выполнилась команда.

$ echo $?

Значение равно 2, потому что команда выдала много ошибок.

Если вы склонны забывать файловый дескриптор stdout и stderr, следующая команда подойдет как нельзя лучше. Это более обобщенный формат предыдущей команды. И stdout, и stderr будут перенаправлены в /dev/null.

$ grep -r hello /sys/ &> /dev/null

Другие примеры

Это интересный пример. Знаете инструмент dd? Это мощный инструмент для преобразования и копирования файлов. Узнайте больше о dd. Используя dd, мы можем проверить скорость последовательного чтения вашего диска. Конечно, это не точное измерение. Однако для быстрого теста это довольно полезно.

$ dd if=<big_file> of=/dev/null status=progress bs=1M iflag=direct

Здесь я использовал Ubuntu 18.04.4 ISO в качестве большого файла.

Аналогичным образом вы также можете проверить скорость загрузки вашего интернет-соединения.

$ wget -O /dev/null <big_file_link>

Надеемся, у вас есть четкое понимание того, что такое файл /dev/null. Это специальное устройство, которое при записи в него отбрасывает, а при чтении из него считывает null. Истинный потенциал этой интересной возможности заключается в интересных bash-скриптах.

Вас интересуют сценарии на bash? Ознакомьтесь с руководством для начинающих по написанию сценариев на bash.

Перевод: https://linuxhint.com/what_is_dev_null/

Oftentimes I run into small bash scripts that use this sort of syntax in if statements:

some command > /dev/null 2>&1

What is the purpose of outputting to /dev/null like that, and what does the 2>&1 mean?

It always seems to work but I’d like to know what it’s doing.

Eliah Kagan's user avatar

Eliah Kagan

115k53 gold badges311 silver badges484 bronze badges

asked Nov 8, 2010 at 14:20

javanix's user avatar

3

>/dev/null redirects the command standard output to the null device, which is a special device which discards the information written to it

2>&1 redirects the standard error stream to the standard output stream (stderr = 2, stdout = 1). Note that this takes the standard error stream and points it to same location as standard output at that moment. This is the reason for the order >/some/where 2>&1 because one needs to first point stdout to somewhere and then point stderr to the same location if one wants to combine both streams in the end.

In practice it prevents any output from the command (both stdout and stderr) from being displayed. It’s used when you don’t care about the command output.

Mikko Rantalainen's user avatar

answered Nov 8, 2010 at 14:31

João Pinto's user avatar

João PintoJoão Pinto

16.8k5 gold badges54 silver badges68 bronze badges

6

STDIN is represented by 0, STDOUT by 1, and STDERR by 2.

/dev/null is the bit-bucket: the place where you dump anything you don’t need.


So, the STDOUT is redirected to the bit-bucket(trash) and the STDERR is redirected to where the STDOUT is located: the bit-bucket.


You can also do this:

>/dev/null 2>/dev/null

answered Nov 8, 2010 at 14:59

Sid's user avatar

SidSid

10.5k10 gold badges46 silver badges47 bronze badges

2

Bash, or the Bourne-Again Shell, is a powerful command-line interface (CLI) that is commonly used in Linux and Unix systems. When working with Bash, it is important to understand how to handle errors that may occur during the execution of commands. In this article, we will discuss various ways to understand and ignore errors in Bash. Bash scripting is a powerful tool for automating and simplifying various tasks in Linux and Unix systems. However, errors can occur during the execution of commands and can cause scripts to fail. In this article, we will explore the various ways to understand and handle errors in Bash. We will look at ways to check the exit status code and error messages of commands, as well as techniques for ignoring errors when necessary. By understanding and properly handling errors, you can ensure that your Bash scripts run smoothly and achieve the desired outcome.

Step-by-step approach for understanding and ignoring errors in Bash:

Step 1: Understand how errors are generated in Bash.

  • When a command is executed, it returns an exit status code.
  • A successful command will have an exit status of 0, while a failed command will have a non-zero exit status.
  • Error messages are generated when a command returns a non-zero exit status code.

Step 2: Check the exit status code of a command.

  • To check the exit status code of a command, you can use the $? variable, which holds the exit status of the last executed command.
  • For example, after executing the command ls non_existent_directory, you can check the exit status code by running echo $? The output
  • will be non-zero (e.g., 2) indicating that the command failed.

Step 3: Check the error message of a command.

  • To check the error message of a command, you can redirect the standard error output (stderr) to a file or to the standard output (stdout) using the 2> operator.
  • For example, you can redirect the stderr of the command ls non_existent_directory to a file by running ls non_existent_directory 2> error.log. Then you can view the error message by running cat error.log.

Step 4: Use the set -e command.

  • The set -e command causes the script to exit immediately if any command exits with a non-zero status. This can be useful for detecting and handling errors early on in a script.
  • For example, if you run set -e followed by ls non_existent_directory, the script will exit immediately with an error message. 

Step 5: Ignore errors when necessary.

  • To ignore errors, you can use the command || true construct. This construct allows you to execute a command, and if it returns a non-zero exit status, the command following the || operator (in this case, true) will be executed instead.
  • For example, you can run rm non_existent_file || true to remove a file that does not exist without exiting with an error.
  • Another way to ignore errors is to use the command 2> /dev/null construct, which redirects the standard error output (stderr) of a command to the null device, effectively ignoring any error messages.
  • Additionally, you can use the command 2>&1 >/dev/null construct to ignore both standard error and standard output.
  • You can also use the command || : construct which allows you to execute a command and if it returns a non-zero exit status, the command following the || operator (in this case, 🙂 will be executed instead. The: command is a no-op command that does nothing, effectively ignoring the error.

Practical Explanation for Understanding Errors

First, let’s examine how errors are generated in Bash. When a command is executed, it returns an exit status code. This code indicates whether the command was successful (exit status 0) or not (non-zero exit status). For example, the following command attempts to list the files in a directory that does not exist:

$ ls non_existent_directory
ls: cannot access 'non_existent_directory': No such file or directory

As you can see, the command generated an error message and returned a non-zero exit status code. To check the exit status code of a command, you can use the $? variable, which holds the exit status of the last executed command.

$ echo $?
2

In addition to the exit status code, you can also check the standard error output (stderr) of a command to understand errors. This can be done by redirecting the stderr to a file or to the standard output (stdout) using the 2> operator.

For example, the following script will redirect the stderr of a command to a file:

$ ls non_existent_directory 2> error.log
$ cat error.log
ls: cannot access 'non_existent_directory': No such file or directory

You can also redirect the stderr to the stdout using the 2>&1 operator, which allows you to see the error message along with the standard output of the command.

$ ls non_existent_directory 2>&1
ls: cannot access 'non_existent_directory': No such file or directory

Another useful tool for understanding errors is the set -e command, which causes the script to exit immediately if any command exits with a non-zero status. This can be useful for detecting and handling errors early on in a script.

$ set -e
$ ls non_existent_directory
# as soon as you hit enter this will exit shell and will close the terminal.

After this command script will exit from the shell if the exit code is nonzero.

Practical Explanation for Ignoring Errors

While it is important to handle errors in Bash scripts, there may be certain situations where you want to ignore errors and continue running the script. In this section, we will discuss different methods for ignoring errors in Bash and provide examples of how to implement them.

Heredoc

Heredoc is a feature in Bash that allows you to specify a string or command without having to escape special characters. This can be useful when you want to ignore errors that may occur while executing a command. The following example demonstrates how to use Heredoc to ignore errors.

#!/bin/bash

# Example of ignoring errors using Heredoc

# The `command` will fail but it will not stop execution
cat <<EOF | while read line; do
  echo $line
done
command that will fail
EOF

# Rest of the script

In this example, the command that is inside the Heredoc will fail, but the script will not stop execution. This is because the output of the command is piped to the while loop, which reads the output and ignores the error.

Pipefail

The pipe fails option in Bash can be used to change the behavior of pipelines so that the exit status of the pipeline is the value of the last (rightmost) command to exit with a non-zero status or zero if all commands exit successfully. This can be useful when you want to ignore errors that may occur while executing multiple commands in a pipeline. The following example demonstrates how to use the pipe fail option to ignore errors.

#!/bin/bash

# Example of ignoring errors using pipefail

# The `command1` will fail but it will not stop execution
set -o pipefail
command1 | command2

# Rest of the script

In this example, command1 will fail, but command2 will continue to execute, and the script will not stop execution.

Undefined Variables

By default, Bash will stop the execution of a script if an undefined variable is used. However, you can use the -u option to ignore this behavior and continue running the script even if an undefined variable is used. The following example demonstrates how to ignore undefined variables.

#!/bin/bash

# Example of ignoring undefined variables

set +u

echo $undefined_variable

# Rest of the script

In this example, the script will not stop execution when an undefined variable is used.

Compiling and Interpreting

When compiling or interpreting a script, errors may occur. However, these errors can be ignored by using the -f option when running the script. The following example demonstrates how to ignore errors when compiling or interpreting a script.

#!/bin/bash

# Example of ignoring errors when compiling or interpreting

bash -f script.sh

# Rest of the script

In this example, the script will continue to run even if there are errors during the compilation or interpretation process.

Traps

A trap is a way to execute a command or a set of commands when a specific signal is received by the script. This can be useful when you want to ignore errors and run a cleanup command instead. The following example demonstrates how to use a trap to ignore errors.

#!/bin/bash

# Example of ignoring errors using a trap

# Set a trap to run the cleanup function when an error occurs
trap cleanup ERR

# Function to run when an error occurs
cleanup() {
  echo "Cleaning up before exiting..."
}

# Command that will cause an error
command_that_will_fail

# Rest of the script

In this example, when the command_that_will_fail causes an error, the script will execute the cleanup function instead of stopping execution. This allows you to perform any necessary cleanup before exiting the script.

Examples of Bash for Error Handling:

Example 1: Error Handling Using a Conditional Condition

One way to handle errors in Bash is to use a conditional statement. The following example demonstrates how to check for a specific error and handle it accordingly.

#!/bin/bash

# Example of error handling using a conditional condition

file=example.txt

if [ ! -f $file ]; then
  echo "Error: $file does not exist"
  exit 1
fi

# Rest of the script

In this example, we check if the file “example.txt” exists using the -f option of the [ command. If the file does not exist, the script will print an error message and exit with a status code of 1. This allows the script to continue running if the file exists and exit if it does not.

Example 2: Error Handling Using the Exit Status Code

Another way to handle errors in Bash is to check the exit status code of a command. Every command in Bash returns an exit status code when it completes, with a code of 0 indicating success and any other code indicating an error. The following example demonstrates how to check the exit status code of a command and handle it accordingly.

#!/bin/bash

# Example of error handling using the exit status code

command1

if [ $? -ne 0 ]; then
  echo "Error: command1 failed"
  exit 1
fi

# Rest of the script

In this example, the script runs the command “command1” and then checks the exit status code using the special variable $?. If the exit status code is not 0, the script will print an error message and exit with a status code of 1.

Example 3: Stop the Execution on the First Error

When running a script, it can be useful to stop the execution on the first error that occurs. This can be achieved by using the set -e command, which tells Bash to exit the script if any command exits with a non-zero status code.

#!/bin/bash

# Stop execution on the first error

set -e

command1
command2
command3

# Rest of the script

In this example, if any of the commands “command1”, “command2” or “command3” fail, the script will exit immediately.

Example 4: Stop the Execution for Uninitialized Variable

Another way to stop execution on error is if an uninitialized variable is used during script execution. This can be achieved by using the set -u command, which tells Bash to exit the script if any uninitialized variable is used.

#!/bin/bash

# Stop execution for uninitialized variable

set -u

echo $uninitialized_variable

# Rest of the script

In this example, if the uninitialized_variable is not defined, the script will exit immediately.

Conclusion

In conclusion, understanding and ignoring errors in Bash is an important aspect of working with the command-line interface. By checking the exit status code of a command, its associated error message, and redirecting the stderr to a file or the stdout, you can understand what went wrong. And by using the command || true, command 2> /dev/null, command 2>&1 >/dev/null, and command || : constructs, you can ignore errors when necessary. It’s always a good practice to test these constructs in a testing environment before using them in production.

In Linux, programs are very commonly accessed using the command line and the output, as such, is displayed on the terminal screen. The output consists of two parts: STDOUT (Standard Output), which contains information logs and success messages, and STDERR (Standard Error), which contains error messages.

Many times, the output contains a lot of information that is not relevant, and which unnecessarily utilizes system resources. In the case of complex automation scripts especially, where there are a lot of programs being run one after the other, the displayed log is huge.

In such cases, we can make use of the pseudo-device file ‘/dev/null‘ to redirect the output. When the output is redirected to /dev/null, it is immediately discarded, and thus, no resource utilization takes place.

Let’s see how to redirect output to /dev/null in Linux.

Let us take an example of the mv command trying to move two files to a particular directory, where one file is moved successfully (displays STDOUT) and the other gives an error while moving (displays STDERR).

$ mv -v tmp.c /etc/apt/sources.list /tmp

Move Multiple Files in Linux

Move Multiple Files in Linux

Note: The '-v' argument to mv displays the success log when a file is moved. Without the flag, nothing is printed to STDOUT.

Now, to redirect only the STDOUT to /dev/null, i.e. to discard the standard output, use the following:

$ mv -v tmp.c /etc/apt/sources.list /tmp 1>/dev/null

Redirect STDOUT to /dev/null

Redirect STDOUT to /dev/null

What does ‘1>/dev/null’ mean?

Here '1' indicates STDOUT, which is a standard integer assigned by Linux for the same. The operator '>', called a redirection operator, writes data to a file. The file specified in this case is /dev/null. Hence, the data is ultimately discarded.

If any other file were given instead of /dev/null, the standard output would have been written to that file.

Similarly, to redirect only the STDERR to /dev/null, use the integer '2' instead of '1'. The integer '2' stands for standard error.

$ mv -v tmp.c /etc/apt/sources.list /tmp 2>/dev/null

Redirect STDERR Output to /dev/null

Redirect STDERR Output to /dev/null

As you can see, the standard error is not displayed on the terminal now as it is discarded in /dev/null.

Finally, to discard both STDOUT and STDERR at the same time, use the following:

$ mv -v tmp.c /etc/apt/sources.list /tmp &>/dev/null

Redirect STDOUT and STDERR Output to /dev/null

Redirect STDOUT and STDERR output to /dev/null

The ampersand character ('&') denotes that both the standard output and standard error has to be redirected to /dev/null and discarded. Hence, in the last screenshot, we do not see any output printed on the screen at all.

Conclusion

In this article, we have seen how to redirect output to /dev/null. The same can be used in either command or in complex Bash scripts which generate a heavy amount of log. In case if the script needs debugging, or has to be tested; in such cases, the log is required to view and analyze the errors properly.

However in cases when the output is already known and anticipated, it can be discarded with /dev/null. If you have any questions or feedback, let us know in the comments below!

Понравилась статья? Поделить с друзьями:
  • Basenamedobjects wmiprovidersubsystemhostjob win32 error 1060
  • Basecomm smx basic comm control unexpected error 23 in askpluginload callback
  • Base game not installed application will exit как исправить
  • Base error unhandled exception inputmapper
  • Base error 7405602 argument parse error