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.
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d99dce41bf42de8 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Linux exit bash built in command
The Linux exit command is a one of many commands built into the bash command, which at the name suggests is used to exit. The command will come up when it comes to writing bash scripts, and I want to have a way to end the process with a certain exit status code. By default the status code should be zero, but that might change in some situations, so it is generally always a good idea to give a status code when using it.
There might not be that much to write about when it comes to the exit command, for the most part I just type it in the bash script and give a status code as the first and only argument. However when it comes to status codes maybe there is a bit more to branch off with when it comes to this topic when it comes to special parameters, mainly the \$\? parameter that can be used to obtain the exit code of the lass ended process.
So then in this post I will be going over a few quick basic Linux exit command examples, and then maybe also touch base on some basic bash script examples that make use of the exit command also.
1 — Linux Exit command basics
In this section I will be going over just some very basic Linux exit command examples, in the process of doing so I will also be going over some other basic features of bash in the process. For example there is the Linux type command that is another bash built in command on top of the Linux exit command that can be used to know that exit is a bash built in command. There is also using bash within bash but passing some arguments to bash to make it run a string as some bash code so the exit command can be used in a terminal window without closing the window each time it is called which is useful when playing around with a command such as the Linux Exit command.
1.2 — Very basic Linux exit example
For a very basic example of the Linux exit command the command can just be called in a terminal window like this.
Doing so will cause the terminal window to close though. This can make it hard to get a sense as to what the exit command does when it comes to status codes. So it is not always a good idea to just work with the exit command directly, unless maybe you do want to just end your terminal window session that way, in which case mission accomplished. Still I think it is called for to go over at least a few more basic examples of the exit command.
1.1 — Using bash -ci, and echo $? to see exit status code
To start to get an idea of what the exit command is really for when making bash scripts, and to do so in a terminal window without having it close on you every time, it might be a good idea to call the bash command itself within the bash prompt, but pass it some options to run a string that contains the Linux exit command. While I am at it I should also touch base on using the Linux echo command to print the exit status code of the last process by passing the value of the exit code special parameter as the argument for the Linux echo command.
Now one can see what the deal is when it comes to using the exit command with a status code argument. This allows for me to define if a script ended with an expected result which would be a zero status, or if some kind of error happened which would be a non zero status. Say I want to write a bash script that checks to see if a process is running and then exit with a zero status if the process is running, or 1 if it is not. I can then use such a script in another script that will call this test script of sorts, and start the process that I am checking in the event that the check script exits with a non zero status. However maybe that should be covered in another section.
1.3 — The type command
The type command is another bash built in command that is worth mentioning when it comes to write about bash built in commands such as the Linux exit command. There are a few ways to know if a command is a bash built in command or not, one of which would be to just read the manual. However there is also the type command that will tell me if a given command is a built in command or not.
2 — Function Bash script example
How about a basic bash script example of the exit command now. This one will make use of a bash function to exit with a given exit code.
Not the most interesting example but the basic idea is there.
3 — Conclusion
The Linux exit command is then one of the many bash built in commands that a Linux user should be aware of when it comes to starting to write bash scripts. It is the standard go to command to make it so that a script will exit with a 0, or non zero exit code status.
Как выйти из скрипта 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, поэтому в этой серии статей представлен ряд советов, приемов, примеров и ошибок, когда дело доходит.
Время для сценариев и процедур Bash изнутри кода
- 09/08/2021
- 0
- БашСценарииАдминистрацияРазработка
В общем, можно использовать время Утилита Bash (см. мужское время для получения дополнительной информации) для запуска программы и получения сводных данных о продолжительности выполнения и использовании системных ресурсов. Но как можно сразу испол.
Операторы Bash if: if, elif, else, then, fi
- 09/08/2021
- 0
- БашПрограммированиеАдминистрацияРазработка
Если вы только начинаете изучать язык программирования Bash, вы скоро обнаружите, что захотите создавать условные операторы. Другими словами, условные утверждения определяют «если условие истинно или ложно, то сделайте то или это, а если верно про.