【发布时间】:2019-03-14 21:54:31
【问题描述】:
我需要从任何其他 bash/shell 脚本中关闭具有唯一名称的特定 gnome 终端窗口。
例如:
$] gnome-terminal --title "myWindow123" -x "watch ls /tmp"
...
...
gnome-terminal 以名称“myWindow123”打开
我需要的只是从我的脚本中杀死那个终端。 bash 中是否也有某种脚本支持?
【问题讨论】:
我需要从任何其他 bash/shell 脚本中关闭具有唯一名称的特定 gnome 终端窗口。
例如:
$] gnome-terminal --title "myWindow123" -x "watch ls /tmp"
...
...
gnome-terminal 以名称“myWindow123”打开
我需要的只是从我的脚本中杀死那个终端。 bash 中是否也有某种脚本支持?
【问题讨论】:
作为当天最丑陋黑客的参赛者:
sh$ TERMPID=$(ps -ef |
grep gnome-terminal | grep myWindow123 |
head -1 | awk '{ print $2 }')
sh$ kill $TERMPID
一个可能更好的选择是在启动时记录终端的 PID,然后被该 pid 杀死:
sh$ gnome-terminal --title "myWindow123" -x "watch ls /tmp"
sh$ echo $! > /path/to/my.term.pid
...
...
# Later, in a terminal far, far away
sh$ kill `cat /path/to/my.term.pid`
【讨论】:
gnome-terminal 的PID 与打开的窗口的PID 不同。
在启动终端的脚本中:
#!/bin/bash
gnome-terminal --title "myWindow123" --disable-factory -x watch ls /tmp &
echo ${!} > /var/tmp/myWindow123.pid
在将杀死终端的脚本中:
#!/bin/bash
if [ -f /var/tmp/myWindow123.pid ]; then
kill $(cat /var/tmp/myWindow123.pid && rm /var/tmp/myWindow123.pid)
fi
【讨论】:
--disable-factory 不再受支持,没有它就无法工作。
这有点难看,但您可以创建一个包装脚本,将 nonce 作为参数,然后杀死 那个。
cat > ~/wrapper.sh < 'EOF'
#!/bin/sh
#Throw away the nonce, and then run the command given
shift
"$@"
EOF
chmod +x ~/wrapper.sh
#Make a random string, so we can kill it later
nonce=`tr -dc '0-9A-Za-z' < /dev/urandom | head -n 10`
gnome-terminal -- ~/wrapper.sh "$nonce" watch ls /tmp
#...
#...
#...
#Kill any command with our nonce as one of its arguments
pkill -f "$nonce"
【讨论】: