Bash Scripts – How to Exit Terminal After Running a Script

bashcommand linescripts

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.

Best Answer

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:

gnome-open <path_to_pdf_file> && exit

*<path_to_pfd_file> = path of the pdf file

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:

<path_to_script> && exit

Or if the script is in the Terminal's current working directory like so:

./<script> && exit

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:

kill -9 $PPID

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.

Related Question