How to have detached persistent remote terminal

Introduction

Imagine you connect to a remote machine with an SSH tunnel and run a time-consuming task there. If your connection drops for a second, your task will shut down immediately. Therefore, you cannot close the terminal or shut down your computer till the task is finished on the remote machine.

To avoid this problem, we can have detached persistent terminals with the aid of screen or tmux. These two need to be installed on the server.

Prerequisites

I assume you have some knowledge of linux commands and ssh command.

screen

screen is usually available on servers. But you can install it on Ubuntu via

sudo apt install screen

screen starts in a terminal with the command

screen

You will see a new terminal opened. In this new terminal, you can run your time-consuming tasks, then press

  • Ctrl+a then d : to detach the terminal.

You will be back in the first terminal. Now you can switch off your local computer and the server will be running your task.

You can create multiple screens for different tasks and detach them. The list of detached terminals (or sessions) can be found from

screen -ls

A detached terminal can be re-attached again:

screen -r id_of_detached_terminal

To kill a screen terminal you have two options:

  • within the that terminal run exit command
  • Outside of that screen, run this command:
screen -X -S screen_id quit

If you have many screens and are suddenly confused about where you are, try

echo $STY

$STY shows the id of the current screen. If it’s empty, you are not in any screen.

tmux

You can install this on a Ubuntu server with

sudo apt install tmux

A new session can be created with

tmux

or give it a special name

tmux new -s name_of_session

In the session, run your time-consuming task and press

  • Ctrl+b then d: to detach the session.

Now you are back to first terminal. You can shut down your local computer safely and task is running on the remote machine.

When you connected to remote again, you can get the list of sessions by

tmux ls

Re-attach a session via:

tmux a -t sesssion_name
Tags ➡ Linux HPC

Subscribe

I notify you of my new posts

Latest Posts

Comments

0 comment