如果您想在通过SSH连接时自动连接到屏幕会话,请将以下代码添加到您.bash_profile或您.bashrc的远程计算机上,它将:
- 每次通过SSH连接时,启动一个新的屏幕会话。
- 重用已经存在的分离屏幕会话,始终从最新会话开始。如果没有可用的分离会话,它将启动一个新的会话。
- 当您打开与计算机的多个SSH连接时,您将获得不同的屏幕会话,因为我们仅重复使用分离的会话。
- 避免循环,以防您将脚本添加到自己的
.bashrc
这是脚本:
#!/bin/bash
#
# Attaches to the first Detached Screen. Otherwise starts a new Screen.
# Only run if we are not already inside a running screen and only if in an SSH session.
if [[ -z "${STY}" && ! -z "${SSH_CLIENT}" ]]; then
detached_screens=($(screen -ls | grep pts | grep -v Attached))
for screen in "${detached_screens[@]}"; do
if [[ "${screen}" == *".pts"* ]]; then
IFS='.pts' read -ra split <<< "${screen}"
for id in "${split[@]}"; do
first_id="${id}"
break
done
break
fi
done
screen -R $first_id
fi
PS:如果要为本地终端启用此功能,请&& ! -z "${SSH_CLIENT}在第一行上将其删除。