How do I Exit a Bash Script?
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.

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.
Как выйти из скрипта Bash
Если вы пишете Баш-скрипт или даже просто выполняя одну из них, важно знать, как выйти из Баш-скрипт .
Существуют комбинации клавиш, которые могут выйти из сценария Bash во время его выполнения в вашем терминале, и есть способы выхода из сценария Bash с использованием различных кодов выхода. Мы покажем вам примеры обоих.
В этом руководстве вы узнаете, как выйти из скрипта Bash либо из скрипта, либо из командная строка пока скрипт выполняется на Linux-система .
В этом уроке вы узнаете:
- Как выйти из скрипта Bash в терминале
- Как выйти из скрипта Bash внутри скрипта
- Как использовать разные коды выхода в скрипте Bash
Как выйти из скрипта Bash в терминале
Это посылает ПОДПИСЬ сигнал прерывания для сценария, и в 99% случаев это должно немедленно завершить работу сценария, который вы выполняете.
Единственное исключение, если ловушка был настроен, чтобы поймать ПОДПИСЬ сигнал. Это имеет место в сценариях, которым необходимо завершить определенную задачу, даже если пользователю срочно нужно остановить сценарий досрочно. В этом случае вам, вероятно, следует просто дождаться завершения скрипта.
В худшем случае вы можете вручную убить скрипт с помощью убийство команда. Смотрите наш другой учебник по Как убить запущенный процесс в Linux .
Как выйти из скрипта Bash внутри скрипта
Естественно, сценарий Bash завершается всякий раз, когда он достигает конца сценария. Но иногда сценарий не предназначен для выполнения до конца, например, в случае с условным оператором.
То выход Команда может быть записана в сценарий Bash, чтобы вручную завершить ее в определенный момент. Код выхода из 0 обычно указывает на то, что скрипт завершил работу без каких-либо ошибок. Код выхода из 1 или выше обычно указывает на то, что при выходе произошла ошибка. Однако разработчик должен решить, что он хочет, чтобы эти коды означали в его скрипте.
Давайте посмотрим на некоторые примеры.
-
Вот базовый скрипт, который будет только выход когда первый пункт если утверждение верно.
Во-первых, мы предлагаем пользователю ввести текст. Затем наш если Оператор проверяет, содержит ли строка текст или она пуста. Если он содержит текст, скрипт эхо введенная строка, а затем выход сценарий. Если пользователь ничего не вводит, пока цикл будет продолжать выполняться и продолжать предлагать их до тех пор, пока не будет введена строка. Вот как это выглядит, когда мы запускаем скрипт:
Теперь мы можем выполнить следующую команду, чтобы увидеть, с каким кодом выхода завершился наш скрипт.
Как и предполагалось, у нас есть код выхода 0 . Обратите внимание, что мы могли бы также просто использовать выход в нашем скрипте вместо выход 0 . Оба выйдут с кодом 0 .
Давайте посмотрим, что произойдет, когда мы выполним скрипт с привилегиями root или без них.
Заключительные мысли
В этом руководстве вы узнали, как выйти из сценария Bash в системной памяти Linux. Это включало выход из сценария во время его выполнения в терминале и выход из сценария Bash, который вы пишете. Вы также видели, как использовать коды выхода, которые позволяют нам указать, завершился ли сценарий успешно или из-за ошибки и т. д.
Подпишитесь на новостную рассылку Linux Career Newsletter, чтобы получать последние новости, информацию о вакансиях, советы по карьере и рекомендации по настройке.
LinuxConfig ищет технического писателя (писателей), ориентированного на технологии GNU/Linux и FLOSS. В ваших статьях будут представлены различные руководства по настройке GNU/Linux и технологии FLOSS, используемые в сочетании с операционной системой GNU/Linux.
Ожидается, что при написании ваших статей вы сможете идти в ногу с технологическим прогрессом в вышеупомянутой технической области знаний. Вы будете работать самостоятельно и сможете выпускать не менее 2 технических статей в месяц.
- 04/03/2022
- 0
- БашПрограммированиеСценарииРазработка

Как обнаружить изнутри Bash-скрипта путь, по которому скрипт находится
- 09/08/2021
- 0
- БашПрограммированиеСценарииАдминистрацияРазработка
Когда вы разрабатываете сложные сценарии Bash и начинаете помещать различные сценарии в папку, где один сценарий взаимодействует с другим, например, запуская быстро становится необходимым убедиться, что мы знаем путь, с которого был запущен сценар.

Регулярные выражения Bash для начинающих с примерами
- 09/08/2021
- 0
- БашПрограммированиеНовичокАдминистрацияРазработка
Использование регулярных выражений в Bash дает вам достаточно возможностей для синтаксического анализа почти любой мыслимой текстовой строки (или даже полных документов) и преобразования их практически в любой желаемый результат. Если вы регулярно.
Баш сломать и продолжить
- 09/08/2021
- 0
- ПетляБашТерминал
Циклы позволяют выполнять одну или несколько команд несколько раз, пока не будет выполнено определенное условие. Однако иногда вам может потребоваться изменить ход цикла и завершить цикл или только текущую итерацию.В Баше сломать и Продолжать опер.
How to terminate a shell script?
I’m working on a supercomputer and have a shell script that will automatically schedule a bunch of jobs for me. Once the script is run, I can terminate manually with Ctrl + C . I was running the script from a unix screen session and terminated the screen , but the script is somehow still running and submitting jobs. It seems to be stuck in a loop and not ending, thus consuming precious core-hours.
I tried ps -u [user] but it doesn’t show up. I know for a fact that it’s still running in the background and just need to kill it.
How to kill a script running in terminal, without closing terminal (Ctrl + C doesn't work)?
I have written a bash script that calls several other programs and executes a bunch of commands. I run this script from the terminal. Now I want to kill the script.
Pressing Ctrl + C sometimes doesn’t cut it, I think because sometimes the script is executing another program, and for some reason the kill signal doesn’t work.
However, if I close the terminal window, it kills the script.
Is there something I can do (a keyboard combination), that is analogous to closing the terminal window, without actually closing the terminal window (I don’t want to lose command history, current directory, output history, etc.)?
![]()
3 Answers 3
You have few options. One is to stop the script ( Ctrl Z ), get the PID of the script and send SIGKILL to the process group.
When a command is executed in a shell, the process it starts and all its children are part of the same process group (in this case, the foreground process group). To send a signal to all processes in this group, you send it to the process leader. For the kill command, process leader is denoted thus:
Where PID is the process ID of the script.
Consider a script test.sh which launches some processes. Say you ran it in a shell:
In another terminal,
In this case, to send a signal to process group created by test.sh , you’d do:
-INT is used to send SIGINT , and so this command is the equivalent of pressing Ctrl C on the terminal. To send SIGKILL :
You only need to stop the script if you can’t open another terminal. If you can, use pgrep to find the PID.
One of the commands that the script launches may be trapping SIGINT , which is probably why Ctrl C is ineffective. However, SIGKILL can’t be trapped, and it is usually a last-resort option. You might want to try SIGTERM ( -TERM ) before going for the kill. Neither SIGKILL or SIGTERM can be set up as a keyboard shortcut the way SIGINT is.
All this is moot if your script doesn’t contain a shebang line. From this SO answer:
Usually the parent shell guesses that the script is written for the the same shell (minimal Bourne-like shells run the script with /bin/sh, bash runs it as a bash subprocess) .
Because of this, when the script is executed, you won’t find a process named after script (or a process with the script’s name in the command line) and pgrep will fail.