Search code examples
bashterminalshxterm

Creating multiple terminals in bash script and keep executing commands?


I have created a bash script to open multiple terminals. However, after all the terminals are opened and have run the first command, I cannot access them and execute the commands I want on the terminal I choose. For example after the code I posted runs, I want to run the insert Hi, 1 command on terminal with title "node5". Can I do that? My current code is the following:

#!/bin/bash
printf "$FBOLD\nPlease enter the port:  $FREG"
read invalue
xterm -title "node1" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node2" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node3" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node4" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node5" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node6" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node7" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node8" -hold -e "node index.js localhost:${invalue}" &
sleep 1
xterm -title "node9" -hold -e "node index.js localhost:${invalue}" &
sleep 1

Edit: To be clearer. I want to execute the commands throught the bash script, because I want to do hundreds of inserts in each terminal. So the process should be automated.


Solution

  • You can use xdotool to automate, here is an example to adapt:

    #!/bin/bash
      
    xterm -title node1 -hold -e 'bash -c "read; echo REPLY=\$REPLY"' &
    sleep 1
    
    xdotool windowfocus --sync $(xdotool search --name node1) # set focus on xterm with title `node1`
    xdotool type "Hello, World!"
    xdotool key Return
    

    Install by apt install xdotool if you are on ubuntu.