Linux exit bash command

Команда 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 .

Читайте также:  Linux which process is using file

Выводы

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

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

Источник

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.

Читайте также:  Linux добавить репозиторий через терминал

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.

$ bash -ci "exit" &> /dev/null; echo $?
0
$ bash -ci "exit 1" &> /dev/null; echo $?
1

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.

#!/bin/bash
exitWith(){
code="${1:0}"
bash -ci "exit ${code}" &> /dev/null
}
if [ "$1" == "foo" ];then
exitWith 0
else
exitWith 1
fi
echo $?
$ chmod 755 exit_script.sh
$ ./exit_script.sh
1
$ ./exit_script.sh baz
1
$ ./exit_script.sh foo
0

Not the most interesting example but the basic idea is there.

Читайте также:  Диспетчер пакетов linux mint

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.

Источник

Can I abort the current running bash command?

Is it possible to manually abort the currently running bash command? So, for example, I’m using ‘find’ but it’s taking ages. how do I manually stop it?

3 Answers 3

Some things won’t respond to Ctrl+C ; in that case, you can also do Ctrl+Z which stops the process and then kill %1 — or even fg to go back to it. Read the section in man bash entitled «JOB CONTROL» for more information. It’s very helpful. (If you’re not familiar with man or the man pager , you can search using / . man bash then inside it /JOB CONTROL Enter will start searching, n will find the next match which is the right section.)

Ctrl+Z is extremely powerful. Use it to put a task in ‘suspend’ mode. You can then use fg to bring the task to the foreground again (just as it was running before), or you can use bg to put the task in to the background (just like if you had launched the command using a & at the end). See linuxreviews.org/beginner/jobs

@Chris Morgan — If a command is running, should it be stopped in midst? This isn’t specific to a runaway process. The use case i’m am referring to a find command that is searching across / . Assuming it’s taking longer than anticipated, should it be stopped? Can it in any way result in corrupt the filesystem?

@Motivated: it depends on the process and how you stop it. In short, SIGTERM (which asks the program to terminate) should be completely safe in all software, and that’s the default for kill . SIGKILL (which forcibly terminates the program), less so, though it should still be fine at almost any point in almost all software (well-behaved software will perform mutations atomically). Something like find doesn’t modify things unless you tell it to (e.g. -delete ), so killing it forcibly is fine.

@ChrisMorgan — To clarify, is CTRL+C a SIGTERM ? What do you mean by well-behaved software will perform mutations atomically ?

Источник

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