Exit terminal after running a bash script
I am trying to write a bash script to open certain files (mostly pdf files) using the gnome-open command. I also want the terminal to exit once it opens the pdf file. I have tried adding exit to the end of my script however that does not close the terminal. I did try to search online for an answer to my question but I couldn’t find any proper one, I would really appreciate it if you guys could help. I need an answer that only kills the terminal from which I run the command not all the terminals would this be possible? The previous answer which I accepted kills all the terminal windows that are open. I did not realize this was the case until today.
Are you running the script in the terminal in the first place? Strictly from command line, there is no reason to open the terminal to do so.
Yes I run the script from the terminal. I didnt realize there was a difference between terminal and command line
I replaced the gnome-open with xdg-open in my script but there is no change. The terminal still remains open
8 Answers 8
If you’re opening just one file, you don’t really need to use a script, because a script is meant to be an easy way to run multiple commands in a row, while here you just need to run two commands (including exit ).
If you want to run exit after a command or after a chain of commands, you can chain it to what you have already by using the && operator (which on success of the previous command / chain of commands will execute the next command) or by using the ; operator (which both on success and on failure of the previous command / chain of commands will execute the next command).
In this case it would be something like that:
exit put at the end of a script doesn’t work because it just exits the bash instance in which the script is run, which is another bash instance than the Terminal’s inner bash instance.
If you want to use a script anyway, the most straightforward way it’s to just call the script like so:
Or if the script is in the Terminal’s current working directory like so:
If you really don’t want to / can’t do that, the second most straightforward way is to add this line at the end of your script:
This will send a SIGKILL signal to the to the script’s parent process (the bash instance linked to the Terminal). If only one bash instance is linked to the Terminal, that being killed will cause Terminal to close itself. If multiple bash instances are linked to the Terminal, that being killed won’t cause Terminal to close itself.
The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate. SIGINT is nearly identical to SIGTERM.
kill $PPID does the same as exit — nothing. And kill -9 $PPID closes all the child windows along with the parent.
+1 for use of kill -9 $PPID When using the GUI option «Run in Konsole» in Debian 11, terminal does not close when using a plan old exit
You can use exec ./your-script .
A terminal emulator like GNOME Terminal quits when the initial process running inside it—which is usually a shell—quits.
If you are already in a terminal and the only thing you want to do before quitting that terminal is to run a particular script (or program), then this means you no longer really need the shell that’s running in it anymore. Thus you can use the shell’s exec builtin to make the shell replace itself with the process created by your command.
- In the case of your script, that’s another shell process—just as how a second shell process is created when you run a script without exec .
The syntax is exec command , e.g., exec ./your-script .
exec : an Example
For example, suppose I have a shell script called count , marked executable, and located in the current directory. It contains:
#!/usr/bin/env bash for i in ; do echo $i; sleep 1; done
This prints the numerals 5 , 4 , 3 , 2 , and 1 , one per second, and then the terminal window closes.
If you run this from something other than the first process run in your terminal—for example, if you ran bash first to start another shell instance—then this brings you back to the shell that created that process, rather than quitting the terminal. (This caveat applies equally to exit -based methods.)
You can use ./your-script; exit .
If you don’t want to tell your shell to replace itself with the new process (via exec ), you can tell it to stick around but quit itself immediately after the new process finishes.
To do this, run your command and the exit command, separated by ; so they can be given on one line.
The syntax is command; exit , e.g., ./your-script; exit .
command; exit vs. command && exit
You may notice this looks similar to the ./your-script && exit method suggested in kos’s and heemayl’s answers. The difference is that:
Which one you want depends on the specific situation. If the command fails, do you want the calling shell (and hosting terminal) to stay up? If so, use && ; if not, use ; .
There is also command || exit , which quits the calling shell only if command reported failure.
This script terminates the terminal and thus the shell and himself.
It mercilessly kills all processes. If you have multiple tabs open in a terminal, then these are also closed.
The problem is, if several terminals are opened and these are child processes of gnome-terminal-server , all terminals will be killed.
In this case, the script should be started in an independent terminal, eg xterm
& disown PPPID=$(awk '' "/proc/$PPID/stat") kill $PPPID
- PPID The PPID is the parent process id, in this case the shell ( e.g. /bin/bash )
- PPPID The PPPID is the parent process id of PPID, in this case, the terminal window
- & disown In the bash shell, the disown builtin command is used to remove jobs from the job table, or to mark jobs so that a SIGHUP signal is not sent to them if the parent shell receives it (e.g. if the user logs out).
- awk » «/proc/$PPID/stat» Gets the value of the fourth column of the file /proc/$PPID/stat (e.g. for /proc/1/stat it returns 0)
Команда exit в Bash и коды выхода
Часто при написании сценариев Bash вам необходимо завершить сценарий при выполнении определенного условия или выполнить действие на основе кода выхода команды.
В этой статье мы рассмотрим встроенную команду exit Bash и статусы выхода выполненных команд.
Статус выхода
Каждая команда оболочки возвращает код выхода, когда она завершается успешно или безуспешно.
По соглашению нулевой код выхода указывает, что команда завершилась успешно, а ненулевое значение означает, что произошла ошибка.
Специальная переменная $? возвращает статус выхода последней выполненной команды:
Команда date завершена успешно, код выхода равен нулю:
Если вы попытаетесь запустить ls в несуществующем каталоге, код выхода будет отличным от нуля:
ls /nonexisting_dir &> /dev/null
echo $?
Код состояния можно использовать для выяснения причины сбоя команды. На странице руководства каждой команды содержится информация о кодах выхода.
При выполнении многокомандного конвейера статус выхода конвейера соответствует состоянию последней команды:
sudo tcpdump -n -l | tee file.out
echo $?
В приведенном выше примере 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 используется для выхода из оболочки с заданным статусом.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.