xterm in Bash – Fix Script Execution Stopping

bashscriptsxterm

I have the following script:

#!/bin/bash

xterm -e ' sh -c "$HOME/TEST/FirstAPP --test;" exec bash'
## script opens the xterm and stops until I press CTRL+C
while true; do
....

this question is related to this question

Why does the script stop at this place? I need to get the xterm called and running and then continue with the code having FirstApp running.

I used the gnome-terminal without problems.

Best Answer

If you want your script to run a command and then continue executing, you need to tun the command in the background (&, see https://unix.stackexchange.com/a/159514/22222). So, change your script to:

#!/bin/bash

xterm -e 'sh -c "$HOME/TEST/FirstAPP --test;"' &
## script opens the xterm and stops until I press CTRL+C
while true; do
....

That will launch the xterm command in the background, keeping the terminal open and FirstAPP running, and will then continue onto the other lines of your script.

The reason it worked with gnome-terminal is because when you run gnome-terminal, it apparently forks itself and returns control to the shell you launched it from. You can see this with strace:

$ strace -e clone gnome-terminal 
clone(child_stack=0x7fef6e44db30, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7fef6e44e9d0, tls=0x7fef6e44e700, child_tidptr=0x7fef6e44e9d0) = 9534
clone(child_stack=0x7fef6dc4cb30, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7fef6dc4d9d0, tls=0x7fef6dc4d700, child_tidptr=0x7fef6dc4d9d0) = 9535
# watch_fast: "/org/gnome/terminal/legacy/" (establishing: 0, active: 0)
clone(child_stack=0x7fef6d391b30, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7fef6d3929d0, tls=0x7fef6d392700, child_tidptr=0x7fef6d3929d0) = 9540
# unwatch_fast: "/org/gnome/terminal/legacy/" (active: 0, establishing: 1)
# watch_established: "/org/gnome/terminal/legacy/" (establishing: 0)
+++ exited with 0 +++

Note the calls to clone which, as explained in man clone does:

   clone() creates a new process, in a manner similar to fork(2).

So, unlike most programs, gnome-terminal will make a clone of itself when launched. The normal way of launching something and then continuing with something else is to use & to launch it in the background.

Related Question