如何编写 shell 脚本来打开四个终端并在每个终端中执行一条命令?

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

所以我正在尝试创建一个 shell 脚本来打开四个终端 windows(最好是 konsoles)和 运行 每个终端中的一个命令,然后保留每个终端终端打开,因此我可以根据需要继续在其中执行命令。

我尝试按照此处列出的说明进行操作:

  1. 我怎样才能制作一个打开终端 windows 并执行的脚本 其中包含命令?

在尝试了这些细节之后,我得到的最好结果如下:

#!/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

编辑: 使用罗伯托的回答,我得到了四个这样的终端,但我无法输入其他命令,请注意没有像 "mycomputername> ":

这样的提示

编辑 2:

我找到了一种更好的方法来做我想做的事。下面的脚本将在单独的终端中执行 cmds 数组中列出的命令。所以 echo 'hello1' 将在一个终端中 运行 ,而 echo 'hello2' 将在另一个终端中 运行 。对于 cmds 数组

中列出的命令,这将继续
!/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

您可以在后台使用 "for" 循环和 运行 xterm 的“&”:


#!/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

控制台

多个windows

#!/usr/bin/env bash
konsole --noclose -e echo Hello terminal 1! &
konsole --noclose -e echo Hello terminal 2! &
konsole --noclose -e echo Hello terminal 3! &
konsole --noclose -e echo Hello terminal 4! &

多个标签

#!/usr/bin/env bash
konsole --noclose --new-tab -e echo Hello terminal 1! &
konsole --noclose --new-tab -e echo Hello terminal 2! &
konsole --noclose --new-tab -e echo Hello terminal 3! &
konsole --noclose --new-tab -e echo Hello terminal 4! &

在 Linux Mint mate 发行版中,这将 运行 <commands> 在 3分离终端 windows:

$ cat START.sh

mate-terminal --execute bash -c "<command1>" 
mate-terminal --execute bash -c "<command2>" 
mate-terminal --execute bash -c "<command3>" 

杀死START.sh不会终止children<commands>.

我发现这很容易:

#!usr/bin/env bash
echo "Enter the value of n:"
read n
for ((i = 0; i < n; i++ ))
do 
   xterm -hold -e <enter command> &
   # In my case, I used : 
   # xterm -hold -e sar -P $i 2 5 &
done

差不多就这些了!祝你有美好的一天:)

注意 : 对于新手,我们将其保存为文件名'.sh'。另外请注意,这将在 n 个不同的终端上执行 n 个不同的命令。如果需要,您可以在每个终端上执行相同的命令,只需从 in do .... done 部分中删除 $i ;)