Linux bash script exit

Команда exit в Bash и коды выхода

Часто при написании сценариев Bash вам необходимо завершить сценарий при выполнении определенного условия или выполнить действие на основе кода выхода команды.

В этой статье мы рассмотрим встроенную команду exit Bash и статусы выхода выполненных команд.

Статус выхода

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

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

Специальная переменная $? возвращает статус выхода последней выполненной команды:

Команда date завершена успешно, код выхода равен нулю:

Если вы попытаетесь запустить ls в несуществующем каталоге, код выхода будет отличным от нуля:

ls /nonexisting_dir &> /dev/nullecho $?

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

При выполнении многокомандного конвейера статус выхода конвейера соответствует состоянию последней команды:

sudo tcpdump -n -l | tee file.outecho $?

В приведенном выше примере echo $? напечатает код выхода команды tee .

Команда exit

Команда exit закрывает оболочку со статусом N Он имеет следующий синтаксис:

Если N не задано, код состояния выхода — это код последней выполненной команды.

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

Примеры

Статус выхода команд может использоваться в условных командах, таких как if . В следующем примере grep завершит работу с нулем (что означает истину в сценариях оболочки), если «строка поиска» найдена в filename :

if grep -q "search-string" filename then echo "String found." else echo "String not found." fi 

При запуске списка команд, разделенных && (И) или || (ИЛИ), статус выхода команды определяет, будет ли выполнена следующая команда в списке. Здесь команда mkdir будет выполнена, только если cd вернет ноль:

cd /opt/code && mkdir project

Если сценарий завершается exit без указания параметра, код выхода из сценария — это код последней команды, выполненной в сценарии.

#!/bin/bash echo "doing stuff. " exit 

Использование только exit — это то же самое, что и exit $? или пропуская exit .

Вот пример, показывающий, как завершить сценарий, если он запущен пользователем без полномочий root:

#!/bin/bash if [[ "$(whoami)" != root ]]; then echo "Only user root can run this script." exit 1 fi echo "doing stuff. " exit 0 

Если вы запустите сценарий как root, код выхода будет нулевым. В противном случае скрипт выйдет со статусом 1 .

Выводы

Каждая команда оболочки возвращает код выхода при завершении. Команда exit используется для выхода из оболочки с заданным статусом.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How do I Exit a Bash Script?

You may have encountered many situations when you have to quit your bash script upon some inconvenience. There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”. This guide will show how the batch script can be quitted using the different exit clauses while executing. Let’s get started by logging in from the Ubuntu 20.04 system first and opening the shell using “Ctrl+Alt+T”.

Читайте также:  Undercover mode kali linux

Example 01: Using Exit 0

The first method we have been utilizing in this example is to use the “exit” statement in the bash script. Create a new file in the shell with the help of a “touch” command and open it in any editor.

The read statement is widely known to get input from the user. Here it will take integer values at run time and save them to the variable “x”. The “if” statement has been checking a condition. If the value of “x” entered by a user is equaled to 5, it will display that the number is matched via the echo statement. The “exit 0” clause has been used here. After executing the “echo” statement, the bash script will be quitted, and no more execution will be performed due to “exit 0”. Otherwise, if the condition doesn’t satisfy, the “echo” statement outside of the “if” statement will be executed.

Run your bash file with the help of a bash query in the shell. The user added 4 as input. As 4 is not equal to 5, it doesn’t run the “then” part of the “if” statement. So, no sudden exit will happen. On the other hand, the echo statement outside of the “if” statement executed states that “Number doesn’t match..” and the program ends here.

Run the same code once again with the bash command. The user added 5 this time. As 5 satisfies the condition, the “echo” statement inside the “then” clause was executed. After that, the program stops quickly due to the use of “exit 0”.

Example 02: Using Exit

Instead of using “exit 0”, you can simply use “exit” in your bash script to exit the code. So, open the same file and update your code. Only the “exit” clause has been changed here, i.e., replaced by “exit”. The whole file remained unchanged. Let’s save the code first using the “Ctrl+S” and quit using “Crl+X”. Let’s execute it to see if it works the same as the “exit 1” clause does or not.

Run the bash file “bash.sh” in the terminal by utilizing the command shown in the attached screenshot. The user entered the value “6” and it didn’t satisfy the condition. Therefore, the compiler ignores the “then” clause of the “if” statement and executes the echo clause outside of the “if” statement.

Run the same file once again. This time the user added 5 as satisfying the condition. Thus the bash script exits right after executing the “echo” clause inside the “if” statement.

Example 03: Using Exit 1

You can also use the “exit” clause to exit the bash script while stating 1 with it at run time. So, open the same file and update your code as we have done before. The only change is “exit 1” instead of “exit” or “exit 0”. Save your code and quit the editor via “Ctrl+S” and “Ctrl+X”.

At first execution, the user added 6 as input. The condition doesn’t satisfy and commands within the “if” statement won’t be executed. So, no sudden exit happened.

On the second attempt, the user added 5 to satisfy the condition. So, the commands within the “if” statement get executed, and the program exits after running the “echo” clause.

Читайте также:  Linux secure delete file

Example 04

Let’s make use of the “exit 1” clause in the bash script upon checking different situations. So, we have updated the code of the same file. After the bash support, the “if” statement has been initialized to check if the currently logged-in user, i.e., “Linux” is not the root user. If the condition satisfies, the echo statement within the “then” clause will be executed, and the program will exit right here. If the currently logged-in account is a root user, it will continue to execute the statements outside of the “if” statement. The program will continue to get two inputs from a user and compute the sum of both integers. The calculated “sum” will be displayed, and then the program will exit.

As the “Linux” account is not a root user of our Ubuntu 20.04, the execution of this code has only executed the “if” statement and clauses between it. The program quits after this.

Example 05: Using “set -e” Built-in

The “set –e” built-in is widely known to exit the program upon encountering the non-zero status. So, we have added 3 twin-named functions with 1 echo statement and a return status clause in each. The “set +e” is initialized before calling the first two methods, and “set –e” is used after that, and two functions are called after that.

Upon execution, both show1 and show2 function’s echo statements will run, and the program will not quit. While after “set –e” the program quits after the execution of the show2() method’s echo statement as it encounters “return 1”. The method show3 will not be called after that.

Upon running this code, we got the output as expected. Upon encountering the return 1 status, the program stopped without executing the “show3()” method.

Conclusion

This guide covers all the possible ways to exit any bash script while writing, executing, or running. Thus, try to implement each example covered in this article to get a more clear understanding.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

How to exit from Bash script

If you are writing a Bash script or even just executing one, an essential thing you will need to know is how to exit from a Bash script.

There are keyboard combinations that can exit from a Bash script while it is executing in your terminal, and there are ways to exit from within a Bash script using various exit codes. We will show you examples of both.

In this tutorial, you will learn how to exit from a Bash script either from within the script or from the command line while the script is executing on a Linux system.

In this tutorial you will learn:

  • How to exit from a Bash script in terminal
  • How to exit from a Bash script within the script
  • How to use different exit codes within a Bash script

Example of how to make a Bash script exit from within the script

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user
Читайте также:  Linux чем посмотреть разрешение экрана

How to exit from a Bash script in terminal

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard. A ^C character will appear in your terminal to indicate a keyboard interrupt.

This sends a SIGINT interrupt signal to the script and, 99% of the time, this should immediately exit the script you are running.

The only exception is if a trap has been setup to catch the SIGINT signal. This is the case in scripts that need to finish up a certain task, even if the user is urgent to stop the script prematurely. In this case, you should probably just wait for the script to finish.

NOTE
Read more about Bash traps in our other tutorial on How to modify scripts behavior on signals using bash traps.

Worst case scenario, you can manually kill the script with the kill command. See our other tutorial on How to Kill a Running Process on Linux.

How to exit from a Bash script within the script

Naturally, a Bash script will exit whenever it reaches the end of the script. But sometimes the script is not meant to make it to the end, such as in the case of a conditional statement.

The exit command can be written into a Bash script to manually terminate it at a certain point. An exit code of 0 usually indicates that the script exited without any errors. An exit code of 1 or higher usually indicates that an error was encountered upon exit. However, it is up to the developer to decide what they want these codes to mean in their script.

Let’s look at some examples.

    Here is a basic script that will only exit when the first clause of the if statement is true.

#!/bin/bash while true; do echo "enter some text" read text if [[ -n $text ]]; then echo "you entered: $text" exit 0 else echo "you didn't enter anything!" fi done

First, we are prompting the user to enter some text. Then, our if statement tests to see if the string contains text or is empty. If it contains text, the script will echo the string entered and then exit the script. If the user does not enter anything, the while loop will continue to execute, and keep prompting them until a string is entered. Here is what it looks like when we execute the script:

$ ./test.sh enter some text hello you entered: hello
#!/bin/bash user=$(whoami) if [ $user = root ]; then echo "Don't execute the script as root" exit 1 fi # do some stuff echo "All done. " exit 0
$ ./test.sh All done. $ echo $? 0 $ sudo ./test.sh Don't execute the script as root $ echo $? 1

Closing Thoughts

In this tutorial, you learned how to exit from a Bash script on a Linux systmem. This included exiting from the script while it is executing in terminal, and how to exit from within a Bash script that you are writing. You also saw how to use exit codes, which allow us to indicate whether the script exited successfully or from an error, etc.

Comments and Discussions

Источник

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