如何从 bash 脚本关闭终端

Und*_*ore 6 bash scripts gnome-terminal

我是这个网站和 Linux 的新手。

我正在尝试制作一个简单的脚本,该脚本将使用新名称打开一个新终端,并从运行脚本的位置关闭旧终端。

我遇到的问题是进程号发生变化。因此,如果我启动进程并输入:echo $$我会看到 10602。进程结束后,如果加载新终端,进程号将更改为 10594。所以我实际上杀死了错误的进程。

此时我使用这段代码:

echo -n "Type new terminal name > "  # displays messagebox
read text                            # load messagebox input
echo "$text" > /etc/terminalname     # write messagebox input to file

gnome-terminal                       # open terminal with new name

kill -9 $PPID                        # this will kill the old terminal
exit                                 # exit script
Run Code Online (Sandbox Code Playgroud)

gle*_*man 4

我假设您在脚本中运行这些命令。

请记住,这是正在运行的$$bash 进程的 pid 。如果您正在运行脚本,则该脚本的 bash 进程是当前交互式 shell 的子进程。如果您在脚本中终止,则您正在终止脚本,而不是父 shell。$$

Bash 将父 pid 存储在$PPID变量中,所以你想要

#!/bin/bash
gnome-terminal &   # launch a new terminal
kill $PPID         # kill this script's parent
Run Code Online (Sandbox Code Playgroud)

我假设父 shell 是从终端生成的 shell,并且您没有更改终端在 shell 退出时关闭的默认行为。

顺便说一句,而不是

echo -n "Type new terminal name > "  # displays messagebox
read text                            # load messagebox input
Run Code Online (Sandbox Code Playgroud)

read -p "Type new terminal name > " text
Run Code Online (Sandbox Code Playgroud)