How to let a shell script spawn itself in a terminal window
08.08.2020 [Software]
I often write scripts, that I don't run from the terminal but by clicking on the file in a file manager. Normally they would then run in the background without showing anything, but it's actually quite simple to let them spawn themselves in a terminal temulator window. I use the following technique for more than 20 years now and it has proven to be one of the most useful things to keep in the back of you mind.


if ! tty -s; then
    gnome-terminal --title="Some title" --window -- "${0}" "${@}"

echo "Press a key to close the window."
read xxx

The tty command returns with an exit code higher than 0 if the input isn't connected to terminal, hence it can be used to check whether a script is running in the background or not. Of course you could check for installed terminal emulators as well to make it compatible across multiple platforms/desktop environments and/or checking environment variables like XDG_CURRENT_DESKTOP to spawn the script in a fitting terminal emulator, but I usually don't do that for my scripts.