Search code examples
bashshellterminalkonsole

Re-run bash script in terminal when started without terminal


I want a script to check if it has been started from within a terminal window. If it was started without window, it shall re-run itself in a visible terminal window.

If found this script line:

tty -s; if [ $? -ne 0 ]; then konsole -e "$0"; exit; fi

It works fine. However since it uses konsole, it is specific to KDE. Is there a more portable solution that runs on Linux system without KDE as well?


Solution

  • No generic solution exists that will work over ALL window systems. however, you can look into implementing a list of common terminal programs. Good thing all take '-e'.

    if [ ... ] ; then
       for t in konsole gnome-terminal xterm ; do
           if type "$t" >/dev/null 2>&1 ; then
              $t -e "$@"
              break
           fi
       done
    

    Also note that 'tty -s' checks if your current stdin is connected to a terminal. You probably want to add a test for valid display ("$DISPLAY"). No point in launching a terminal window, if not running under some window manager.

    You can improve code further by checking for environment variables that let you know if you are running under terminal: 'GNOME_TERMINAL_SCREEN', 'XTERM_SHELL', or checking of '$TERM' for 'xterm*'.