Я использую терминал так часто для выполнения быстрых команд, а затем оставляю его в фоновом режиме, чтобы в итоге я получал 20 сеансов терминала, пока я работаю. Это связано с тем, что очень просто использовать комбинацию клавиш и ввести команду.
Есть ли способ настроить ярлык, чтобы я запустил последнее окно терминала вместо создания нового?
Я использую гейку, и я очень доволен ею. Нажмите F12, появится окно терминала, снова нажмите F12, он исчезнет, но продолжит работать в фоновом режиме. Также: выглядит действительно круто.
Вы можете поместить скрипт ниже под комбинацию клавиш. Если вы нажмете комбинацию клавиш, окно (и) терминала исчезнет (полностью).
Единственное, что вам нужно (один раз) - добавить идентификационную строку в имя окна вашего терминала (в окне терминала есть одно и то же имя в большинстве случаев)
Установите оба параметра xdotool и wmctrl:
sudo apt-get install xdotool
sudo apt-get install wmctrl
Скопируйте сценарий в пустой файл, сохраните его как hide_terminal.py В разделе «Глава» установите идентификационную строку имени окна терминала. Запустите ее под комбинацией клавиш: python3 /path/to/hide_terminal.py
#!/usr/bin/env python3
import subprocess
import os
home = os.environ["HOME"]
hidden_windowid = home+"/.window_id.txt"
get = lambda cmd: subprocess.check_output(cmd).decode("utf-8")
# --- set the identifying string in the terminal window's name below (you mentioned "Terminal"
window_idstring = "Special_window"
# ---
def execute(cmd):
subprocess.check_call(cmd)
w_id = [l.split()[0] for l in get(["wmctrl", "-l"]).splitlines() if window_idstring in l]
if len(w_id) !=0:
for w in w_id:
execute(["xdotool", "windowunmap", w])
with open(hidden_windowid, "a") as out:
out.write(w+"\n")
else:
try:
with open(hidden_windowid) as read:
for w in [w.strip() for w in read.readlines()]:
try:
execute(["xdotool", "windowmap", w])
except subprocess.CalledProcessError:
pass
with open(hidden_windowid, "wt") as clear:
clear.write("")
except FileNotFoundError:
pass
Это то же самое, что и ответ Джейкоба Влайма, только что написанный в bash:
#!/usr/bin/env bash
## window_name will be the first argument passed or, if no
## argument was given, "Terminal"
window_name=${1:-"Terminal"}
## Get the list of open terminals
terms=( $(wmctrl -l | grep "$window_name" | cut -d ' ' -f 1) )
## If all terminals are hidden
if [ -z "${terms[0]}" ]
then
## Read the IDs of hidden windows from .hidden_window_id
while read termid
do
xdotool windowmap "$termid"
done < ~/.hidden_window_id
## If there are visible terminals
else
## Clear the .hidden_window_id file
> ~/.hidden_window_id
## For each open terminal
for i in "${terms[@]}"
do
## Save the current ID into the file
printf "%s\n" "$i" >> ~/.hidden_window_id
## Hide the window
xdotool windowunmap "$i"
done
fi
Если вы сохраните его как ~/bin/show_hide.sh, вы можете запустить его, указав строку идентификации любого окна, которое вы хочу спрятаться. Если строка не указана, она будет работать на Terminal:
show_hide.sh Terminal
Я использую gnome-shell с расширением «Drop Down Terminal», ярлык по умолчанию - TAB, но его легко изменить.
Эта простая команда wmctrl поднимет окно с заданной строкой в заголовке или если в нем нет окна, запустите команду.
wmctrl -a <str> || <command to launch application>
например, для gedit Я могу использовать [!d1 ]
wmctrl -a gedit || gedit
Чтобы найти подходящую строку для вашего окна приложения, откройте приложение и запустите
wmctrl -l
для меня работал следующий подход:
#!/usr/bin/env bash
# Written by Eric Zhiqiang Ma (http://www.ericzma.com)
# Last update: Jul. 9, 2014
# Read the tutorials at
# http://www.systutorials.com/5475/turning-gnome-terminal-to-a-pop-up-terminal/
# Required tools: xdotool
terminal="gnome-terminal"
stat_file="/dev/shm/actiavte-termianl.term.$USER"
termtype="Terminal"
wait_sec=1
max_wait_cnt=4
# parse options first
if [ "$1" != "" ]; then
terminal="$1"
fi
term_exists () {
allterms=`xdotool search --class "$termtype"`
for e in $allterms; do [[ "$e" == "$1" ]] && return 0; done
return 1
}
create_terminal () {
echo "Create new terminal"
$terminal --maximize &
exists=1
wait_cnt=0
until [ "$exists" == "0" ]; do
# sleep a while
sleep $wait_sec
# Note that the focus window may be from a terminal that
# already exists; the makes create_terminal choose the existing terminal
# Making the wait_sec large enough so that the terminal can be created and
# displayed can make the false choosing more unlikely.
term=$(xdotool getwindowfocus)
term_exists "$term"
exists=$?
# avoid infinite wait
let wait_cnt=wait_cnt+1
if [ $wait_cnt -gt $max_wait_cnt ]; then
echo "Wait for too long. Give up."
term=""
exists=0
fi
done
echo "Created terminal window $term"
# save the state
echo "$term" >$stat_file
}
# read the state
if [ -f $stat_file ]; then
term=$(cat $stat_file)
fi
# check whether it exists
term_exists "$term"
exists=$?
if [[ "$exists" != "0" ]]; then
create_terminal
exit 0
fi
# check whether it is already activated
curwin=$(xdotool getwindowfocus)
if [ "$term" == "$curwin" ]; then
# deactivate (minimize) the terminal if it is currently activated
xdotool windowminimize $curwin
else
# activate the terminal if it is not currently activated
xdotool windowactivate $term
fi
exit 0
, а затем просто давал ему разрешения на выполнение и привязывал скрипт к ключу в настройках.
источник:
http://www.systutorials.com/5475/turning-gnome-terminal-to-a-pop-up-terminal/