How to run a command within a previously opened terminal with gnome-terminal command in a shell script?

Solution 1:

You can't, except perhaps on a hackish way using keypress simulation. e.g. xdotool to switch back to the first window, then paste some commands.

There may be better ways to do what you want. However, in order for us to give better suggestions, we need to know what you really want to achieve.

Solution 2:

Try with the following demo running A and B

A master script creates a temporary file (in /tmp) and starts a-script and b-script in xterm windows.

Install

sudo apt install xterm

Put all the scripts into a dedicated directory, make them executable and run

./master

master:

#!/bin/bash

echo "$0 start"

b4a=$(mktemp)

nohup xterm -fa default -e ./a-script "$b4a" 2> /dev/null &
nohup xterm -fa default -e ./b-script "$b4a" 2> /dev/null &

if test -f "$b4a"
then
 rm "$b4a"
fi
echo "$0 finish"

a-script:

#!/bin/bash

echo "$0 start"
echo "$0 can do things here ..."
while ! test -f "$1"
do
 sleep 1
 echo -n "."
done
echo ""
echo "$0 can do things here ..."
rm "$1"
read -p "$0: Press enter to finish "

b-script:

#!/bin/bash

echo "$0 start"
echo "$0 can do things here ..."
sleep 5
touch "$1"
read -p "$0: Press enter to finish "