Linux exit command shell

Any way to exit bash script, but not quitting the terminal

When I use exit command in a shell script, the script will terminate the terminal (the prompt). Is there any way to terminate a script and then staying in the terminal? My script run.sh is expected to execute by directly being sourced, or sourced from another script. EDIT: To be more specific, there are two scripts run2.sh as

when I run it by . run2.sh , and if it hit exit codeline in run.sh , I want it to stop to the terminal and stay there. But using exit , the whole terminal gets closed. PS: I have tried to use return , but echo codeline will still gets executed.

the exit command should not terminate your terminal session/login. if you use exit 0 to terminate the script after success, when you run your script ex: ./test.sh you should see the output but your console will remain open.

You could use the shell command, that opens in fact a shell terminal. My own experience however is that this doesn’t happen with exit . Exit normally gives back the control to the parent script.

Читайте также:  Linux default group for user

This makes no sense to me. It only kills process (aka the terminal) if called from the top level (globally.) And why would you do that? At the top level, it exits gracefully by itself after completing anyway. Am I missing something here?

@IgnacioVazquez-Abrams your comment does little except to make the OP feel bad. It sort of hints that the problem has to do with sourcing the script, but why not just say that instead of making someone feel bad for trying it? After all, it’s a kind of subtle point that exec and source run differently in terms of shell. Ah, but I see that five people have joined you in being mean.

17 Answers 17

The «problem» really is that you’re sourcing and not executing the script. When you source a file, its contents will be executed in the current shell, instead of spawning a subshell. So everything, including exit, will affect the current shell.

Instead of using exit , you will want to use return .

Although correct, this is not a great answer. It ignores that the calling script may declare variables or functions that that called script needs access to. Better to explain how to set a return code and then process it in runs.sh @ruakh has the better answer to this question.

What if the function is a nested call? i.e. a calls b, b calls c, c wants to immediately exit a and b.

Source is almost the same as copy paste. It’s better to use sh

Yes; you can use return instead of exit . Its main purpose is to return from a shell function, but if you use it within a source -d script, it returns from that script.

Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source ) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source .

Источник

Exit Command in Linux

In Linux, the exit command is used to terminate the shell (the current login session) in which it is run. Also, similar to a C program, the exit command is used in shell scripts to terminate the script. Moreover, it returns a value to the script’s parent process.

What Will We Cover?

In this guide, we will see an overview of the exit command in Linux with some use cases.

The Exit Command and Exit Status

You can also use the exit command to specify the exit status of the shell. The exit status is a numeric value that is returned to the parent process when the shell terminates.

The exit status can be used to indicate the success or failure of the command. For example, a shell script might use the exit status to determine whether to perform certain actions based on the success or failure of a command.

To specify the exit status, you can use the exit command followed by a number. For example, exit 0 indicates a successful exit, while exit 1 indicates a failure.

The exit command accepts a single, optional argument which becomes the script’s exit status.

When no argument is passed, the exit status defaults to the exit status of the last command that is executed. In order to see the exit status, use the echo “$?” command.

Examples of Exit Codes (Exit Status)

The exit command is crucial to indicate that a severe error has occurred since the calling processes typically consider the exit codes other than zero as failure cases. If you need a general error trap in your scripts, try using the exit code snippet.

Let’s see some examples of using the exit code in a script and on a terminal:

Example 1: Using the Exit Command with File Expression

Let’s first take an example of a script:

#!/bin/bash
# test-file: Evaluate the status of a file
FILE = / proc / uptime
if [ -e " $FILE " ] ; then # Check the existence of file.
if [ -f " $FILE " ] ; then # Check if it is a regular file.
echo " $FILE is a regular file."
fi
if [ -b " $FILE " ] ; then # Checks if it is a block file
echo " $FILE is a block device"
fi
else
echo " $FILE is neither a regular nor a block file or may not exist"
exit 1
fi
exit

The script performs an evaluation on the file that is allocated to the constant “FILE” and outputs the results as it runs.

First, it checks if it is a regular file or a block file. If the condition is not satisfied, it prints the message in the else block.

The first exit command sets the exit status of the script in case of failure (exit value as 1). The second exit command is a formal expression. This means that when the script completes its execution to the end, it has the exit status of the last command which, in this case, is the exit command. This last exit command will result in success (exit value as 0):

Example 2: Using True and False Commands with the Exit Command

Additionally, entering a simple true or false argument causes the terminal to quit with 0 status code and shows 0 as true. If we instead provide a false statement, the exit status will be 1 since false exits with code 1. Let’s see this in a practical manner. First, issue the true command and check the exit status:

Now, issue the false command and again check the exit status:

Example 3: Interrupting a Script with Ctrl+C

When a user hits Control-C, a special signal known as SIGINT is sent. This interrupts the script or running program, causing it to exit with the code 130. Let’s take an example: suppose you started searching a file with the find command:

The search is still going on. Then, you suddenly interrupted it with “Ctrl+C”. This causes the command to stop with the exit code 130.

Example 4: The Shell Variable SHLVL and the Exit Command

With the shell-specific variable, SHLVL, you can see how many levels deep in the Bash shell you are. Each new shell session that is opened in a terminal increases the session count, starting at 1 for the initial session. If SHLVL is > 1, the exit command closes the current session. In the same way, if the SHLVL is = 1, the exit command logs you out of the system.

To simply put it, when you type “exit” at the command prompt and press Enter, the shell closes (close the current login session) and you will be returned to the shell or command prompt from which you launched it.

Conclusion

We have seen the different use cases of the exit command and the interpretation of the exit status in each case. There are many different exit code numbers for different purposes. Note that these exit codes are Bash specific. If you tend to use other shells such as C-shell or tcsh, the results may differ.

About the author

Ali Imran Nagori

Ali imran is a technical writer and Linux enthusiast who loves to write about Linux system administration and related technologies. You can connect with him on LinkedIn
.

Источник

Команда 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 используется для выхода из оболочки с заданным статусом.

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

Источник

exit command in Linux with Examples

exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed. Syntax:

Options for exit command –

  • exit: Exit Without Parameter After pressing enter, the terminal will simply close.
  • exit [n] : Exit With Parameter After pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status – “0” means the program has executed successfully. “1” means the program has minor errors.
  • exit n : Using “sudo su” we are going to the root directory and then exit the root directory with a return status of 5. After returning it will show how to display the return status code. echo $? command is used to see the last return status.
  • exit –help : It displays help information.

Источник

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