Exit from shell linux

The “exit” Command in Linux [5 Practical Examples]

There are multiple ways to exit or log out from the current shell or job in the Linux environment. When we take a leave from shell windows, it may affect the backend jobs. So, we need a proper way so that there will be no impact even though the user or shell window will exit from the Linux environment. You can exit the shell where it is running by using the exit command in Linux. In this article, I will describe all the features and uses of the exit command in Linux with multiple examples.

A. Description

The exit command is used to end or close the current login session in the Linux ecosystem. Shell or bash jobs as well as the Linux CLI can be closed using this simple command.

B. Syntax

The syntax of the exit command in Linux is very simple which is as below:

exit [INTEGER_VALUE] USER_NAME

Note: You can provide the integer value and which can be used for further system calls. Again, there are no OPTIONS available for the exit command in Linux.

Practical Examples of the “exit” Command in Linux

The exit is a helpful command which helps to take a safe exit from any shell or job or bash jobs. In the section below I will show you some useful applications with exit commands in Linux.

Example 1: Exiting from Current Shell Using the “exit” Command

You can take an exit from the current shell by simply typing exit. Here, I will take an exit from the current shell by using the exit command. To do the same, follow the steps below. Steps to Follow: ➊ At first open the Ubuntu Terminal. ➋ Type the following command in the command prompt:

➌ Now, press the ENTER button. Output: Before executing the exit command, you can see the terminal.Terminal is operating before executing the exit command in linux.After executing the exit command, the terminal has closed. The terminal has closed after executing the exit command in linux.

Example 2: Exiting from the Root User’s Shell Using the “exit” Command

You can take an exit from the root user by simply typing exit. Here, I will take an exit from the root user’s shell by using the exit command. To do the same follow the steps below. Steps to Follow: ➊ At first open the Ubuntu Terminal. ➋ Type the following command in the command prompt:

Читайте также:  Arch linux установка habr

➌ Now, press the ENTER button. By typing your password, you will log in as root_user. ➍ Then, type the following command in the command prompt:

The process of exiting the root user with the exit command

➎ Now, press the ENTER button. Output: In the image below, you can see that the root user takes an exit by leaving a messageexit” in the terminal.

Example 3: Exit Command With Default Value

In the Linux environment, every job or command has a default exit code. The default successful value exit code is “0” for each command. If you get any other value except “0” then there will be some issue in the job or command. Steps to Follow: ➊ At first open the Ubuntu Terminal. ➋ Type the following command in the command prompt:

➌ Now, press the ENTER button. You will get the output “ hello world“ in the terminal. ➍ Then type the following command in the command prompt:

➎ Again, press the ENTER button. You will get ‘0’ which means there is no issue in the command. ➏ Now, Type the following command in the command prompt:

➐ Press the ENTER button again. You will get a ‘>’ sign which is due to any unexpected error. ➑ press CTRL+C and then type the following command in the command prompt:

The default value of the exit command in linux.

After executing the echo $? command, you will not get ‘0’ as before, which means there is an issue. ➒ Now, press the ENTER button. Output: When the echo “hello world” command is executed successfully there you get ‘0’ as the exit code but after executing a faulty command the exit code becomes non-zero.

  • The “echo” Command in Linux [7 Practical Examples]
  • The “alias” Command in Linux [3 Practical Examples]
  • The “unalias” Command in Linux [3 Practical Examples]

Example 4: Exit Command With Manual Value

You can set a manual exit code for a job. To do so, you have to prepare a shell job that can be written with the nano command. In the section below I will show you, how to set a manual value as an exit code. Here I set the exit code 60.

Steps to Follow:

➊ At first open the Ubuntu Terminal.

➋ Type the following command in the command prompt:

Open nano terminal.

➌ Now, press the ENTER button.

➍ type the following text in the nano text editor.

#!/usr/bin/bash echo "Hello world" exit 60

Bash script for exit command in linux with manual value.

➎Put the following command into action.

Читайте также:  Checking memory size linux

➏ Now, press the ENTER button.

You will get the output as “Hello world”

➐Then, execute the command below.

Exit Command With Manual Value

After executing the echo $? command, you will get the manual exit code on the terminal shown below.

Example 5: Exit Command Help

You can get help about the exit command by using the help command. The process is very simple and you can get help by the process described below.

Steps to Follow:

➊ At first open the Ubuntu Terminal.

➋ Type the following command in the command prompt:

➌ Now, press the ENTER button.

Help page of the exit command.

You can see the help page on the terminal and can get the required help with the exit command.

Conclusion

I’ve demonstrated the operation of the exit command in this article. Additionally, I have included some helpful examples. If you carefully read this article, you will be able to use the exit command effectively on your own.

Similar Readings

  • The “bash” Command in Linux [5 Practical Examples]
  • The “clear” Command in Linux [3 Practical Examples]
  • The “declare” Command in Linux [7 Practical Examples]
  • The “export” Command in Linux [8 Practical Examples]
  • The “source” Command in Linux [3 Practical Examples]
  • The “hash” Command in Linux [6 Practical Examples]

Источник

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

Читайте также:  Delete all files except one linux

Вот пример, показывающий, как завершить сценарий, если он запущен пользователем без полномочий 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 to exit sh program?

I bungled the commands and wrote sh -man Now I’ve entered a program called sh-3.2 that is seemingly impossible to exit. Ctrl c , Ctrl z , or Ctrl x does not work. exit , quit , q , : q also does not work. All google answers are for exiting shell scripts programmatically.

5 Answers 5

Ctrl + D does the trick for me.

Actually it is the -n flag that introduces this behaviour. It is meant to do only syntax checking of the commands, but doesn’t actually execute them.

Try ctrl+d that should kill the shell.

Hold Ctrl and press p q . This solved my issue.

If you shell exit is pre planned then use,

Or you can program to handle SIGTERM and other signals a sample tutorial

Or if you want to stop already running shell script

Or find the pid and kill it.

ps -ax | grep shell_name pkill -9 PID_of_shell 

Try also typing ` which is in the same key as ~ on the keyboard, and then press Return . Ctrl + D kills the terminal but ` won’t.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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