我有三个脚本需要在启动Ubuntu机器时运行,它们启动我在开发环境中使用的服务。
为了做到这一点,我手动打开三个终端并输入命令。
有没有办法创建一个脚本,可以打开三个终端并在每个终端中执行一个命令?(每个命令应该在单独的终端窗口中,这样我就可以看到它们的输出)。
为了做到这一点,我手动打开三个终端并输入命令。
有没有办法创建一个脚本,可以打开三个终端并在每个终端中执行一个命令?(每个命令应该在单独的终端窗口中,这样我就可以看到它们的输出)。
gnome-terminal -- command
或者
xterm -e command
或者
konsole -e command
terminal -e command
在 konsole 中,有一个 --noclose
标志。
在 xterm 中,有一个 -hold
标志。
在 gnome-terminal
中,进入 编辑 -> 配置文件首选项 -> 标题。点击 命令 选项卡。从标记为 当命令退出时 的下拉菜单中选择 保持终端打开。您应该为此创建一个新的配置文件,并使用以下命令执行:
gnome-terminal --window-with-profile=配置文件名称 -e 命令
command
被引用时,gnome-terminal -e command
才能正常工作。所以这样是不起作用的:gnome-terminal -e "echo hello world; sleep 3"
,但这样是可以的:gnome-terminal -e "bash -c 'echo hello world; sleep 3'"
。唉。 - bgoodrgnome-terminal -- command
- dallonsi--
代替-e
,就像@dallonsi评论中的示例一样。 - Tim--hold
应该在 -e
之前使用。换句话说,-e
后面应该只跟命令。 - SaidbakRx-terminal-emulator
-e
选项来执行命令(我已经验证了 konsole
和 gnome-terminal
)。命令后面的参数将传递给被调用的命令。Bash 在我的终端中无法保持打开状态,需要额外的脚本来获取一个终端:#!/bin/sh
"$@"
exec "$SHELL"
/home/user/hacky
并且设置为可执行文件,你可以使用以下命令来运行你的脚本:x-terminal-emulator -e /home/user/hacky your-script optional arguments here
bash
)或者添加一行代码,比如read -p "按回车键继续"
来“修复”这个问题。 - Lekensteyncd xxx && start.sh
。解释器将&&视为命令的第二部分(这是合乎逻辑的),但如果我对其加引号,它会尝试将整个内容作为一个大参数执行。 - Richardx-terminal-emulator
打开的是 Terminator,但我的默认终端是 "Preferred Applications" 中的 xfce4-terminal
。为什么会这样呢? - Aaron Frankex-terminal-emulator
是通过update-alternatives
系统配置来进行设置的,而"Preferred Applications"则是在用户配置中进行配置和存储的。 - Lekensteyn2020年2月17日更新:这个答案现在可能已经过时了。
考虑点击此链接并使用我提供的另一个答案:打开带有多个选项卡并执行应用程序的终端
cd /etc; ls
。末尾的$SHELL
部分强制shell保持打开状态,以便您可以看到其输出并继续使用它(我在Stack Overflow的其他地方学到了这一点)。gnome-terminal --tab --title="test" --command="bash -c 'cd /etc; ls; $SHELL'"
gnome-terminal --tab --title="tab 1" --command="bash -c 'cd /etc; ls; $SHELL'" --tab --title="tab 2" --command="bash -c 'cd ~; ls; $SHELL'" --tab --title="tab 3" --command="bash -c 'cd ~/temp3; ls; $SHELL'"
gnome-terminal
= 打开一个gnome终端--tab
= 为接下来的内容打开一个独立的选项卡--title="tab 1"
= 将此选项卡命名为"tab 1"--command="bash -c 'cd /etc; ls; $SHELL'"
= 运行bash -c 'cd /etc; ls; $SHELL'
命令,这只是我举例编写的命令;以下是它的作用:bash -c
表示这是一个bash 'c'ommand(命令)cd /etc
= 切换到"/etc"路径ls
= 列出该目录的内容$SHELL
= 这个神秘的片段是必需的,以保持shell打开状态,以便您可以使用它。如果您希望打开shell、运行命令,然后关闭,请删除此部分。但是,我希望选项卡保持打开状态,以便我可以进行编程魔法。 :)--tab
部分重新开始,生成选项卡2,再次生成选项卡3。根据您的喜好进行自定义。xdotool key --clearmodifiers Super+d
,我在我的show-desktop.desktop文件中使用这个命令,按下Windows键
+ D
来切换显示桌面,就好像是人类按下了这些键。我相信你可以编写脚本按下正确次数的Ctrl
+ PgUp
或Ctrl
+ PgDn
来选择你想要的选项卡,因为这就是人类手动切换选项卡的方式。 - Gabriel Staplesgnome-terminal --tab --title="tab 1"
这个例子正是我所寻找的。然而,在 Ubuntu 22.10 上,我遇到了以下警告:`# 选项“--command”已被弃用,并可能在以后的 gnome-terminal 版本中被移除。~/.bash_aliases
文件,找到gs_open_default_tabs
函数作为示例。让所有这些都正常工作确实有些棘手,但根据我的测试,在Ubuntu 16.04、18.04、20.04和22.04上都可以正常运行。 - Gabriel Staples#!/bin/bash
/etc/init.d/ccpd status
#!/bin/bash
gnome-terminal -e "/etc/init.d/ccpd status" --window-with-profile=NAMEOFTHEPROFILE
另一篇帖子打算使用[]
作为占位符
这里的"NAMEOFTHEPROFILE"将被替换为"在命令退出时保持终端的配置文件的名称"。
[]
只是一个占位符。 - Karthik T--window-with-profile=配置文件名称
- Karthik T虽然晚了近十年,但这是我用Python的答案。
在下面的 .gif
中,我从现有的终端启动了程序,并运行屏幕录制以展示登录时的样子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#==============================================================================
#
# dellstart - Autostart GUI applications on Dell Fileserver
#
#==============================================================================
'''
CALL:
dellstart
REQUIRES:
sudo apt install xdotool
'''
from __future__ import print_function # Must be first import
import os
import time
BASHRC_TIME = 2 # Seconds to load ~/.bashrc
WINDOW_TIME = .5 # Secpmds fpr window to appear
commands = [ 'gnome-terminal &', # Launch terminal in background
'sleep '+str(BASHRC_TIME), # Bash command wait a sec
'move x y', # Move windows to x and/or y
# 'move 2100 1000', # triple monitor setup
'xdotool type "cd ~"', # Change to home directory
'xdotool key Return', # Enter Key
'xdotool type "./ssh-activity"', # Suspend after 15 minutes
'xdotool key Return', # Enter Key
'title SSH\ Activity', # Window title (escape spaces)
'xdotool key Control_L+Shift_L+T', # Open new terminal tab
'sleep '+str(BASHRC_TIME), # Bash command wait a sec
'xdotool type "cd ~/askubuntu"', # Change to working directory
'xdotool key Return', # Enter Key
'title Ask\ Ubuntu', # Window title (escape spaces)
'gedit', # Last 5 files will open up
'move x y', # Move windows to x and/or y
# 'move 3849 2266', # triple monitor setup
]
""" NOTE: To discover window coordinates, arrange on desktop and type:
wmctrl -lG
"""
def process_commands(command_list):
for command in command_list:
if command.endswith('&'):
# Launch in background and get window ID opened
active_pid, active_win = launch_command(command)
if active_pid == 0:
print("ERROR launching", command, \
"Aborting 'dellstart' script")
exit()
elif command.startswith('move'):
move_window(command, active_win)
elif command.startswith('title'):
terminal_title(command)
elif command.startswith('gedit'):
gedit()
else:
run_and_wait(command)
def launch_command(ext_name):
''' Launch external command in background and return PID to parent.
Use for programs requiring more than .2 seconds to run.
'''
all_pids = get_pids(ext_name) # Snapshot current PID list
all_wins = get_wins(all_pids) # Snapshot of windows open
new_pids = all_pids
new_wins = all_wins
sleep_count = 0 # Counter to prevent infinite loops
os.popen(ext_name) # Run command in background
while new_pids == all_pids: # Loop until new PID is assigned
new_pids = get_pids(ext_name) # Snapshot current PID list
if sleep_count > 0: # Don't sleep first time through loop
time.sleep(.005) # sleep 5 milliseconds
sleep_count += 1
if sleep_count == 1000: # 10 second time-out
print('launch_ext_command() ERROR: max sleep count reached')
print('External command name:',ext_name)
return 0
pid_list = list(set(new_pids) - set(all_pids))
if not len(pid_list) == 1:
print('launch_command() ERROR: A new PID could not be found')
return 0, 0
time.sleep(WINDOW_TIME) # Give time for window to appear
new_wins = get_wins(all_pids) # Snapshot of windows open
win_list = list(set(new_wins) - set(all_wins))
if not len(win_list) == 1:
#print('launch_command() ERROR: New Window ID could not be found')
#suppress error message because we aren't using window ID at all
return int(pid_list[0]), 0
# Return PID of program we just launched in background
return int(pid_list[0]), int(win_list[0])
def run_and_wait(ext_name):
''' Launch external command and wait for it to end.
Use for programs requiring less than .2 seconds to run.
'''
result = os.popen(ext_name).read().strip()
#print('run_and_wait() command:', ext_name)
return result
def get_pids(ext_name):
''' Return list of PIDs for program name and arguments
Whitespace output is compressed to single space
'''
all_lines = []
# Just grep up to first space in command line. It was failing on !
prog_name = ext_name.split(' ',1)[0]
all_lines = os.popen("ps aux | grep -v grep | grep " + \
"'" + prog_name + "'").read().strip().splitlines
PID = []
for l in all_lines():
l = ' '.join(l.split()) # Compress whitespace into single space
PID.append(int(l.split(' ', 2)[1]))
return PID
def get_wins(all_pids):
''' Return list of all windows open under PID list
Currently unncessary because we work on active window '''
windows = []
for pid in all_pids:
all_lines = os.popen('xdotool search --pid ' + str(pid)). \
read().strip().splitlines
for l in all_lines():
windows.append(int(l))
return windows
def move_window(line, active_win):
''' Move window to x y coorindates on Desktop
If the letter x or y is passed, that dimension remains unchanged eg:
xdotool getactivewindow windowmove 100 100 # Moves to 100,100
xdotool getactivewindow windowmove x 100 # Moves to x,100
xdotool getactivewindow windowmove 100 y # Moves to 100,y
'''
line = ' '.join(line.split()) # Compress whitespace to single space
x = line.split(' ')[-2]
y = line.split(' ')[-1]
# We don't need to pass window ID as last active window defaults
all_lines = os.popen('xdotool getactivewindow windowmove ' + x + ' ' + y). \
read().strip().splitlines
for l in all_lines():
print(l)
def terminal_title(new_title):
''' Rather awkward calling xdotool which chokes on double quotes and bash
via python which chokes on backslashes.
Simple format (if it worked) would be:
command = r'PS1="${PS1/\\u@\\h: \\w/' + title + '}"'
The bash function copied from is:
function termtitle() { PS1="${PS1/\\u@\\h: \\w/$@}"; }
Reference for xdotool keycodes:
https://gitlab.com/cunidev/gestures/-/wikis/xdotool-list-of-key-codes
'''
title = new_title.split(' ', 1)[1] # Strip out leading "title" token
command = 'xdotool type PS1='
run_and_wait(command)
run_and_wait('xdotool key quotedbl')
command = 'xdotool type $'
run_and_wait(command)
run_and_wait('xdotool key braceleft')
command = 'xdotool type PS1/'
run_and_wait(command)
run_and_wait('xdotool key backslash')
run_and_wait('xdotool key backslash')
command = 'xdotool type u@'
run_and_wait(command)
run_and_wait('xdotool key backslash')
run_and_wait('xdotool key backslash')
command = 'xdotool type "h: "'
run_and_wait(command)
run_and_wait('xdotool key backslash')
run_and_wait('xdotool key backslash')
command = 'xdotool type "w/"'
run_and_wait(command)
command = 'xdotool type "' + title + '"'
run_and_wait(command)
run_and_wait('xdotool key braceright')
run_and_wait('xdotool key quotedbl')
run_and_wait('xdotool key Return')
def gedit():
last_modified_files = gedit_recent_files()
command = 'gedit '
for f in last_modified_files:
command=command+'"'
command=command+f
command=command+'" '
# Open gedit with last five modfied files
command=command+' &'
active_pid, active_win = launch_command(command)
if active_pid == 0:
print("ERROR launching", command, \
"Aborting 'dellstart' script")
exit()
def gedit_recent_files():
''' Get list of gedit 5 most recent files:
grep --no-group-separator -B5 'group>gedit' ~/.local/share/recently-used.xbel | sed -n 1~6p | sed 's# <bookmark href="file:///#/#g' | sed 's/"//g'
/home/rick/python/mmm added=2020-05-02T15:34:55Z modified=2020-11-19T00:43:45Z visited=2020-05-02T15:34:56Z>
/home/rick/python/mserve added=2020-07-26T16:36:09Z modified=2020-11-28T01:57:19Z visited=2020-07-26T16:36:09Z>
'''
command = "grep --no-group-separator -B5 'group>gedit' " + \
"~/.local/share/recently-used.xbel | " + \
"sed -n 1~6p | sed 's# <bookmark href=" + '"' + \
"file:///#/#g' | " + "sed 's/" + '"' + "//g'"
recent_files = []
times = []
all_lines = os.popen(command).read().strip().splitlines
uniquifier = 1 # gedit can give all open files same time
for l in all_lines():
fname = l.split(' added=', 1)[0]
trailing = l.split(' added=', 1)[1]
modified = trailing.split(' modified=', 1)[1]
modified = modified.split('Z', 1)[0]
# TODO: 2038
d = time.strptime(modified, '%Y-%m-%dT%H:%M:%S')
epoch = time.mktime(d)
epoch = int(epoch)
recent_files.append(fname)
try:
times.index(epoch)
# gedit has given multiple files the same modification time
epoch += uniquifier
uniquifier += 1
except:
pass # Not a duplicate time
times.append(epoch)
N=5
top_files = []
if N > len(times):
# Less than 5 most recent files in list
N = len(times)
if N == 0:
# No most recent files in list
return top_files # return empty list
# Store list in tmp to retrieve index
tmp=list(times)
# Sort list so that largest elements are on the far right
times.sort()
#print ('5 most recent from lists and indices')
for i in range(1, N+1):
top_files.append(recent_files[tmp.index(times[-i])])
return top_files
if __name__ == "__main__":
process_commands(commands)
# end of dellstart
BASHRC_TIME
,以使程序运行更快。我的 ~/.bashrc
中有很多函数在运行,而您的可能会运行得更快。hacky_function()
{
"$@"
exec "$SHELL"
}
更新至我现在使用的版本(2022年)
#!/usr/bin/expect -f
# Get a Bash shell
spawn -noecho bash
# Wait for a prompt
expect "$ "
send "sudo /home/user/script.sh arg"
# Hand over control to the user
interact
exit
--command
引起的警告。gnome-terminal\
--tab\
--title="TAB 1" -- bash -c "cd ~; ls; $SHELL"
gnome-terminal\
--tab\
--title="TAB 2" -- bash -c "cd ~/Desktop; ls; $SHELL"\