shell

Summary

There are times when you’re at the terminal, connected to a host, you run a command but you really want to disconnect and go somewhere else, this short article will show you how.

Basics

First you want to start your program script in the background, to do this you have two options.

Either:

your_command.sh &

or

your_command.sh
ctrl+z

Either works but the ctrl+d method will let you easily answer any question your program may have before launching the main process. If you choose the ctrl+d method you’ll need to issue a further command:

bg

Now your program is running in the background, you can see it with the command jobs. It is still however attached to your terminal and any output the program has will still be shown on your terminal. If you quit your session now the program may terminate early.

To prevent this you will need one further command:

disown

Once this is called your jobs will be cleared from your terminal and instead runs unattached. Now you can disconnect and have a coffee.

Reattach

This is tricky and may not work, but if you need to start another terminal and grab the process, you’ll need something similar to reptyr

apt install -y reptyr
pacman -S reptyr

With this command you can steal a processes terminal, all you’ll need is the process id.

ps -ax | grep mycommand.sh

then

reptyr -s PID

This might not work if the command or script has created subprocesses however you may be able to get it to work with a -T option.

Using Screen

Sometimes a program or script refuses to detach, running docker commands seem to suffer from this particularly. It’s simple to work around the with screen

screen
./command.sh

You now want to put screen into the background, do that by pressing ctrl+a followed with z

You can now follow the previous steps and do:

bg
disown

Recap

mycommand.sh &
disown
exit

Edits

2022-Feb-05: Added screen method