【问题标题】:Close gnome-terminal with specific title from another script/shell command从另一个脚本/shell 命令关闭具有特定标题的 gnome-terminal
【发布时间】:2019-03-14 21:54:31
【问题描述】:

我需要从任何其他 bash/shell 脚本中关闭具有唯一名称的特定 gnome 终端窗口。

例如:

$] gnome-terminal --title "myWindow123" -x "watch ls /tmp"

...
...

gnome-terminal 以名称“myWindow123”打开

我需要的只是从我的脚本中杀死那个终端。 bash 中是否也有某种脚本支持?

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    作为当天最丑陋黑客的参赛者:

    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`
    

    【讨论】:

    • 我们可以期待 bash 中的脚本吗??
    • 您的解决方案都不起作用,因为gnome-terminal 的PID 与打开的窗口的PID 不同。
    【解决方案2】:

    在启动终端的脚本中:

    #!/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 参数以允许脚本从 gnome-terminal 运行。
    • --disable-factory 不再受支持,没有它就无法工作。
    【解决方案3】:

    这有点难看,但您可以创建一个包装脚本,将 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      相关资源
      最近更新 更多