首页 > 解决方案 > 在脚本中,如何使用 ttyecho 获取生成的终端 shell 的 pid 以在其中执行命令?

问题描述

我正在使用 ttyecho(可以安装yay -S ttyecho-git)在单独的终端中执行命令,如下所示:

urxvt &
sudo ttyecho -n /proc/<pid-of-new-urxvt>/fd/0 <command>

它不起作用,因为 /proc/pid-of-new-urxvt/fd/0 是指向父终端的 /dev/pts/x 的符号链接。在生成的 urxvt 中,我碰巧运行了 zsh。因此,如果我使用该 zsh 进程的 pid,它就可以工作:

sudo ttyecho -n /proc/<pid-of-new-zsh-within-new-urxvt>/fd/0 <command>

运行时如何获取在新 urxvt 进程中生成的新 zsh 进程的 pid urxvt &?还是有不同的解决方案来达到相同的结果?

标签: linuxbashshellterminaltty

解决方案


pgrep -P <pid-of-new-urxvt>给出子 zsh 进程的 pid。感谢@user1934428 进行头脑风暴

这是生成的 bash 脚本:

urxvt &
term_pid=$!

# sleep here makes us wait until the child shell in the terminal is started
sleep 0.1

# we retrieve the pid of the shell launched in the new terminal
shell_pid=$(pgrep -P $term_pid)

# ttyecho executes the command in the shell of the new terminal and gives back control of the terminal so you can run further commands manually
sudo ttyecho -n /proc/${shell_pid}/fd/0 "$@"

因此,当我启动“script ls”时,它会打开一个新终端,运行 ls,并在终端仍然打开的情况下返回提示。我只需要在 sudoers 文件中添加 ttyecho。


推荐阅读