Search code examples
linuxshellunixscriptingxterm

How to write a shell script to open four terminals and execute a command in each?


So I'm trying to create a shell script to do open up four terminal windows (konsoles preferably) and run a command in each and then keep each of those terminals open so I can continue to execute commands in them if desired.

I tried following the instructions listed here:

  1. How to create a shell script to launch 3 terminals and execute a set of commands in each?

and

  1. How can I make a script that opens terminal windows and executes commands in them?

and after trying those details the best I have is the following:

#!/bin/bash

# some older test, doesn't work and complains and I get this message on command line: "QApplication::qAppName: Please instantiate the QApplication object first"
# I also can't enter text after command executes
#echo "Hello World!"
#exec konsole --noclose -e cat ~/.aliases 

# opens terminal but then I can't control terminal afterwards    
xterm -hold -e "echo Hello My World"

# didn't do anything
#exit 0

# didn't do anything except make me type exit an extra time where I executed my shell script
#$SHELL

EDIT: Using Roberto's answer I get four terminals like this, but I can't enter additional commands, notice how there is no prompt like "mycomputername> ":

enter image description here

EDIT 2:

I found an even better way to do what I want. The script below will execute the commands listed in the cmds array in a separate terminal. So echo 'hello1' will run in one terminal, and echo 'hello2' will run in another terminal. This will continue for as many commands listed in the cmds array

!/bin/bash
# Shell script to open terminals
# and execute a separate command in each

# Commands to run (one per terminal)
cmds=('echo 'hello1'', 'echo 'hello2'')

# Loop through commands, open terminal, execute command
for i in "${cmds[@]}"
do
    xterm -e "$i && /bin/tcsh" &
done

Solution

  • You could use a "for" loop, and a "&" to run xterm in background:


    #!/bin/bash
    
    # some older test, doesn't work and complains and I get this message on command line: "QApplication::qAppName: Please instantiate the QApplication object first"
    # I also can't enter text after command executes
    #echo "Hello World!"
    #exec konsole --noclose -e cat ~/.aliases
    
    for i in 1 2 3 4
    do
    # opens terminal but then I can't control terminal afterwards
    xterm -hold -e "echo Hello My World" &
    done
    
    # didn't do anything
    #exit 0
    
    # didn't do anything except make me type exit an extra time where I executed my shell script
    #$SHELL