One point missed in the existing answers is show how to inherit the error traps. The bash
shell provides one such option for that using set
-E
If set, any trap on
ERR
is inherited by shell functions, command substitutions, and commands executed in a subshell environment. TheERR
trap is normally not inherited in such cases.
Adam Rosenfield’s answer recommendation to use set -e
is right in certain cases but it has its own potential pitfalls. See GreyCat’s BashFAQ — 105 — Why doesn’t set -e (or set -o errexit, or trap ERR) do what I expected?
According to the manual, set -e exits
if a simple commandexits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a
while
oruntil
keyword, part of thetest in a if statement
, part of an&&
or||
list except the command following thefinal && or ||
,any command in a pipeline but the last
, or if the command’s return value is being inverted via!
«.
which means, set -e
does not work under the following simple cases (detailed explanations can be found on the wiki)
-
Using the arithmetic operator
let
or$((..))
(bash
4.1 onwards) to increment a variable value as#!/usr/bin/env bash set -e i=0 let i++ # or ((i++)) on bash 4.1 or later echo "i is $i"
-
If the offending command is not part of the last command executed via
&&
or||
. For e.g. the below trap wouldn’t fire when its expected to#!/usr/bin/env bash set -e test -d nosuchdir && echo no dir echo survived
-
When used incorrectly in an
if
statement as, the exit code of theif
statement is the exit code of the last executed command. In the example below the last executed command wasecho
which wouldn’t fire the trap, even though thetest -d
failed#!/usr/bin/env bash set -e f() { if test -d nosuchdir; then echo no dir; fi; } f echo survived
-
When used with command-substitution, they are ignored, unless
inherit_errexit
is set withbash
4.4#!/usr/bin/env bash set -e foo=$(expr 1-1; true) echo survived
-
when you use commands that look like assignments but aren’t, such as
export
,declare
,typeset
orlocal
. Here the function call tof
will not exit aslocal
has swept the error code that was set previously.set -e f() { local var=$(somecommand that fails); } g() { local var; var=$(somecommand that fails); }
-
When used in a pipeline, and the offending command is not part of the last command. For e.g. the below command would still go through. One options is to enable
pipefail
by returning the exit code of the first failed process:set -e somecommand that fails | cat - echo survived
The ideal recommendation is to not use set -e
and implement an own version of error checking instead. More information on implementing custom error handling on one of my answers to Raise error in a Bash script
Содержание
- How to Exit When Errors Occur in Bash Scripts
- Exit When Any Command Fails
- Exit Only When Specific Commands Fail
- Conclusion
- Suggested Articles
- Exit a Bash Script: Exit 0 and Exit 1 Explained
- Exit a Bash Script With Error
- What Are Exit 0 and Exit 1 in a Bash Script?
- More About The Status of the Bash Exit Command
- An Example of Script Failure
- Bash If Else Applied to $? Variable
- Conclusion
- Перехват и обработка ошибок в bash
- Проверка статуса завершения команды
- Выход из сценария при ошибке в Bash
- Как использовать коды завершения в Bash-скриптах
- Что такое коды завершения
- Что происходит, когда коды завершения не определены
- Как использовать коды завершения в Bash-скриптах
- Проверяем коды завершения
- Создаём собственный код завершения
- Как использовать коды завершения в командной строке
- Дополнительные коды завершения
How to Exit When Errors Occur in Bash Scripts
By Evan Sangaline | September 11, 2017
It’s a common issue that scripts written and tested on GNU/Linux don’t run correctly on macOS–or vice versa–because of differences between the GNU and BSD versions of the core utils. Error messages can get drowned in the script output, making it far from obvious that something isn’t executing correctly. There are a couple of easy fixes to avoid problems like this, but they rely on some bash features that you may not be familiar with if you don’t do a ton of scripting. I’ll summarize my two approaches here and hopefully they’re of some use to you if you’re looking for a how-to guide for this specific problem.
Exit When Any Command Fails
This can actually be done with a single line using the set builtin command with the -e option.
Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code. We can get a little fancier if we use DEBUG and EXIT traps to execute custom commands before each line of the script is run and before the script exits, respectively. Adding the following lines will allow us to print out a nice error message including the previously run command and its exit code.
For example, if we run ls —fake-option then we’ll see an informative error message as follows.
Exit Only When Specific Commands Fail
The global solution is often fine, but sometimes you only care if certain commands fail. We can handle this situation by defining a function that needs to be explicitly invoked to check the status code and exit if necessary.
That bottom line isn’t strictly necessary, but it allows us to use !! and have it expand to the last command executed. For example, we can check explicitly for an error like this
will pass the exit code of the previous command as the first argument to exit_on_error() and then !! will expand to ls —fake-option as the second and third arguments. The second and third arguments–plus any further arguments if they were there–are then recombined by slicing $ <@:2>.
This approach will print the same error message as the one in the previous section, but will only check the commands that are explicitly followed by exit_on_error calls.
Conclusion
Hopefully you found one of these two methods helpful! If you’re ever struggling with any devops or infrastructure issues then please reach out about our consulting services in these areas.
Suggested Articles
If you enjoyed this article, then you might also enjoy these related ones.
Источник
Exit a Bash Script: Exit 0 and Exit 1 Explained
Why would you exit from a Bash script?
Let’s say you are writing a script…there’s one thing that is almost certain…
At some point, your script is likely to break because of unexpected conditions you might have not considered.
So, what can you do about it?
How can you exit a Bash script in case of errors?
Bash provides a command to exit a script if errors occur, the exit command. The argument N (exit status) can be passed to the exit command to indicate if a script is executed successfully (N = 0) or unsuccessfully (N != 0). If N is omitted the exit command takes the exit status of the last command executed.
In this guide you will learn how to use the exit command in your scripts to make them more robust and to provide a great experience to those who are using your scripts.
Let’s get started.
Table of Contents
Exit a Bash Script With Error
What can you do to write robust scripts that don’t break in unexpected ways in case of errors?
The answer to this question is: don’t forget error handling.
Instead of “hoping” that nothing will go wrong with your program, you can predict possible failures and decide how your program will react to those.
How will you handle a failure if it occurs? What will the user see?
We will have a look at how error handling works in Bash scripting (or Shell scripting in general).
These concepts apply to all programming languages even if the way error handling is implemented varies between programming languages.
To handle errors in Bash we will use the exit command, whose syntax is:
Where N is the Bash exit code (or exit status) used to exit the script during its execution.
Different values of N are used to indicate if the script exits with success or failure.
But, why different exit codes depending on the success or failure of a script?
Because often other programs will be calling your script and they will need to be able to understand if everything goes well with the execution of your script or not as part of their error handling.
Let’s have a look at what exit 1 means.
What Are Exit 0 and Exit 1 in a Bash Script?
How do you exit a Bash script on error?
The standard convention is the following:
Bash exit code | Meaning |
Zero (0) | Success |
Non-zero (1, 2, 3, etc…) | Failure |
As you can see from the table above, failures can be represented with any non-zero exit codes.
For instance:
- 1 may be used if incorrect arguments are passed to the script
- 2 if the script cannot find a file it needs
- 3 if the file it needs has an incorrect format
- And so on…
You can be creative and use non-zero Bash exit codes to be very clear about the reason why your script has failed.
So, going back to the exit command.
What happens when it gets executed?
The exit command returns an exit code back to the shell.
Here’s an example…
Let’s write a script called exit_status.sh:
So, here we are passing the exit code 0 to the exit command.
How can we verify that this is actually the code passed by the script back to the shell?
We use the $? variable. Remember it, this is very important!
$? is a variable that contains the exit code of the last command executed.
And how can we read its value?
Using the echo command, in the same way we print the value of any variable:
Voilà, here is the 0 exit code.
And what happens if we remove “exit 0” from the script?
Run the script again and check the value of $?:
We still get the 0 exit code back…
So, nothing changed…why?
Because every command we execute, including the echo command (the only command in our script) returns an exit code.
And in this case the echo command executed as part of the script is returning a 0 exit code because the echo “Exit command test” command is executed successfully.
More About The Status of the Bash Exit Command
I will show you an example of how the exit code is applied to the execution of any commands.
This is really important in your Bash knowledge and I want to make sure it’s clear to you.
Here is an example with the cat command (this applies to all commands)…
I open a shell on my computer and in the current directory I have the following files:
If I use the cat command to see the content of the file test_file1 the exit code stored in the variable $? after the execution of the cat command is 0 because the execution of the cat command is successful:
If by mistake I try to print the content of the file test_file3 (that doesn’t exist), the value of the variable $? is not 0.
In this case it’s 1, but it can have other values different than zero. This is useful to represent multiple types of errors for a given command:
If you have any questions please let me know in the comments below.
An Example of Script Failure
Now let’s modify the echo command in the simple script we have used before.
We want run it with an incorrect syntax and see if it exits with a non-zero exit code.
Remove the double quotes at the end of the echo command as shown below:
If we execute the script we see the message “syntax error: unexpected end of file“:
And the exit code is 2. So a non-zero exit code as we expected.
As mentioned before, remember the $? variable because it makes a big difference in the way you handle errors and you make your scripts robust.
The Bash if else statement can also be used to write more complex logic that checks the value of the $? variable and takes different actions based on that.
Bash If Else Applied to $? Variable
Let’s see how you can use a Bash if else statement together with the $? variable.
The following script tries to create a subdirectory tmp/project in the current directory.
In the condition of the if statement we verify if the value of the variable $? is different than 0. If that’s the case we print an error message and exit the script with exit code 1.
The else branch prints a successful message and it’s executed only if the value of $? is 0.
Let’s run the script:
The mkdir command fails because the tmp directory doesn’t exist and as expected the exit status of the script is 1.
I want to see what happens if I update the mkdir command in the script to include the -p flag that creates the tmp directory if it doesn’t exist:
And here is the output of the script:
This time the directory gets created successfully and the exit code returned by the script is zero as expected (the else branch of the if else statement gets executed).
Conclusion
We went through quite a lot!
Now you know:
- Why exit 0 and exit 1 are used in Bash scripts.
- How you can use the variable $? to read the exit code returned by a command (or script)
- The way to use a Bash if else statement together with the $? variable.
And now it’s your turn…
What kind of failures do you want to handle in your script?
Let me know in the comments! 😀
Related FREE Course: Decipher Bash Scripting
Источник
Перехват и обработка ошибок в bash
Написание надежного, без ошибок сценария bash всегда является сложной задачей. Даже если вы написать идеальный сценарий bash, он все равно может не сработать из-за внешних факторов, таких как некорректный ввод или проблемы с сетью.
В оболочке bash нет никакого механизма поглощения исключений, такого как конструкции try/catch. Некоторые ошибки bash могут быть молча проигнорированы, но могут иметь последствия в дальнейшем.
Проверка статуса завершения команды
Всегда рекомендуется проверять статус завершения команды, так как ненулевой статус выхода обычно указывает на ошибку
Другой (более компактный) способ инициировать обработку ошибок на основе статуса выхода — использовать OR:
С помощью оператора OR, выполняется тогда и только тогда, когда возвращает ненулевой статус выхода.
В качестве второй команды, можно использовать свою Bash функцию обработки ошибок
В Bash имеется встроенная переменная $?, которая сообщает вам статус выхода последней выполненной команды.
Когда вызывается функция bash, $? считывает статус выхода последней команды, вызванной внутри функции. Поскольку некоторые ненулевые коды выхода имеют специальные значения, вы можете обрабатывать их выборочно.
Выход из сценария при ошибке в Bash
Когда возникает ошибка в сценарии bash, по умолчанию он выводит сообщение об ошибке в stderr, но продолжает выполнение в остальной части сценария. Даже если ввести неправильную команду, это не приведет к завершению работы сценария. Вы просто увидите ошибку «command not found».
Такое поведение оболочки по умолчанию может быть нежелательным для некоторых bash сценариев. Например, если скрипт содержит критический блок кода, в котором не допускаются ошибки, вы хотите, чтобы ваш скрипт немедленно завершал работу при возникновении любой ошибки внутри этого блока . Чтобы активировать это поведение «выход при ошибке» в bash, вы можете использовать команду set следующим образом.
Вызванная с опцией -e, команда set заставляет оболочку bash немедленно завершить работу, если любая последующая команда завершается с ненулевым статусом (вызванным состоянием ошибки). Опция +e возвращает оболочку в режим по умолчанию. set -e эквивалентна set -o errexit. Аналогично, set +e является сокращением команды set +o errexit.
Если необходимо, чтобы при любом сбое в работе конвейеров также завершался сценарий bash, необходимо добавить опцию -o pipefail.
Для «защиты» критический блока в сценарии от любого типов ошибок команд или ошибок конвейера, необходимо использовать следующую комбинацию команд set.
Источник
Как использовать коды завершения в Bash-скриптах
Инструменты автоматизации и мониторинга удобны тем, что разработчик может взять готовые скрипты, при необходимости адаптировать и использовать в своём проекте. Можно заметить, что в некоторых скриптах используются коды завершения (exit codes), а в других нет. О коде завершения легко забыть, но это очень полезный инструмент. Особенно важно использовать его в скриптах командной строки.
Что такое коды завершения
В Linux и других Unix-подобных операционных системах программы во время завершения могут передавать значение родительскому процессу. Это значение называется кодом завершения или состоянием завершения. В POSIX по соглашению действует стандарт: программа передаёт 0 при успешном исполнении и 1 или большее число при неудачном исполнении.
Почему это важно? Если смотреть на коды завершения в контексте скриптов для командной строки, ответ очевиден. Любой полезный Bash-скрипт неизбежно будет использоваться в других скриптах или его обернут в однострочник Bash. Это особенно актуально при использовании инструментов автоматизации типа SaltStack или инструментов мониторинга типа Nagios. Эти программы исполняют скрипт и проверяют статус завершения, чтобы определить, было ли исполнение успешным.
Кроме того, даже если вы не определяете коды завершения, они всё равно есть в ваших скриптах. Но без корректного определения кодов выхода можно столкнуться с проблемами: ложными сообщениями об успешном исполнении, которые могут повлиять на работу скрипта.
Что происходит, когда коды завершения не определены
В Linux любой код, запущенный в командной строке, имеет код завершения. Если код завершения не определён, Bash-скрипты используют код выхода последней запущенной команды. Чтобы лучше понять суть, обратите внимание на пример.
Этот скрипт запускает команды touch и echo . Если запустить этот скрипт без прав суперпользователя, команда touch не выполнится. В этот момент мы хотели бы получить информацию об ошибке с помощью соответствующего кода завершения. Чтобы проверить код выхода, достаточно ввести в командную строку специальную переменную $? . Она печатает код возврата последней запущенной команды.
Как видно, после запуска команды ./tmp.sh получаем код завершения 0 . Этот код говорит об успешном выполнении команды, хотя на самом деле команда не выполнилась. Скрипт из примера выше исполняет две команды: touch и echo . Поскольку код завершения не определён, получаем код выхода последней запущенной команды. Это команда echo , которая успешно выполнилась.
Если убрать из скрипта команду echo , можно получить код завершения команды touch .
Поскольку touch в данном случае — последняя запущенная команда, и она не выполнилась, получаем код возврата 1 .
Как использовать коды завершения в Bash-скриптах
Удаление из скрипта команды echo позволило нам получить код завершения. Что делать, если нужно сделать разные действия в случае успешного и неуспешного выполнения команды touch ? Речь идёт о печати stdout в случае успеха и stderr в случае неуспеха.
Проверяем коды завершения
Выше мы пользовались специальной переменной $? , чтобы получить код завершения скрипта. Также с помощью этой переменной можно проверить, выполнилась ли команда touch успешно.
После рефакторинга скрипта получаем такое поведение:
- Если команда touch выполняется с кодом 0 , скрипт с помощью echo сообщает об успешно созданном файле.
- Если команда touch выполняется с другим кодом, скрипт сообщает, что не смог создать файл.
Любой код завершения кроме 0 значит неудачную попытку создать файл. Скрипт с помощью echo отправляет сообщение о неудаче в stderr .
Создаём собственный код завершения
Наш скрипт уже сообщает об ошибке, если команда touch выполняется с ошибкой. Но в случае успешного выполнения команды мы всё также получаем код 0 .
Поскольку скрипт завершился с ошибкой, было бы не очень хорошей идеей передавать код успешного завершения в другую программу, которая использует этот скрипт. Чтобы добавить собственный код завершения, можно воспользоваться командой exit .
Теперь в случае успешного выполнения команды touch скрипт с помощью echo сообщает об успехе и завершается с кодом 0 . В противном случае скрипт печатает сообщение об ошибке при попытке создать файл и завершается с кодом 1 .
Как использовать коды завершения в командной строке
Скрипт уже умеет сообщать пользователям и программам об успешном или неуспешном выполнении. Теперь его можно использовать с другими инструментами администрирования или однострочниками командной строки.
В примере выше && используется для обозначения «и», а || для обозначения «или». В данном случае команда выполняет скрипт ./tmp.sh , а затем выполняет echo «bam» , если код завершения 0 . Если код завершения 1 , выполняется следующая команда в круглых скобках. Как видно, в скобках для группировки команд снова используются && и || .
Скрипт использует коды завершения, чтобы понять, была ли команда успешно выполнена. Если коды завершения используются некорректно, пользователь скрипта может получить неожиданные результаты при неудачном выполнении команды.
Дополнительные коды завершения
Команда exit принимает числа от 0 до 255 . В большинстве случаев можно обойтись кодами 0 и 1 . Однако есть зарезервированные коды, которые обозначают конкретные ошибки. Список зарезервированных кодов можно посмотреть в документации.
Адаптированный перевод статьи Understanding Exit Codes and how to use them in bash scripts by Benjamin Cane. Мнение администрации Хекслета может не совпадать с мнением автора оригинальной публикации.
Источник
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.