The simple way is to use screen. This program is commonly installed on Ubuntu server. If not installed, enter the command below to install screen:
sudo apt-get install screen
How to use screen?
Let’s use the very simple way. Run this command:
You will see the screen version and other information.
Next, press enter. Now you’re in the screen already.
To list all running screen:
You should see something like this:
15686.pts-0.ubuntu (06/23/2019 03:03:19 PM) (Attached)
15686 = screen number
pts-0.ubuntu = screen title
Now from here you can run any script. Example, I will run my own bash script.
This script will continue to run even my terminal is close.
How to detached from this screen?
ctrl [hold] a [release] d
How to terminate screen?
If you are attached on the screen, simply press:
ctrl [hold] a [release] [press] k
If you are detached from screen, simply enter this command:
screen -XS [session number] quit
screen -XS [screen title] quit
How to reattach to the session?
To get into the session
screen -r [session id or name]
How to switch between screen?
Ctrl+a press n (Next screen)
Ctrl+a press p (Previous screen)
How to run a script directly on screen with title?
screen -dmS screen_title ./your_script.sh
screen -dmS screen_title python3 python_script.py
*The screen_title is the title or name of your screen. Let’s see the currently running screen
Show list of screen
How to use screen on crontab
Using cron, you can schedule a script to run on screen. First, we need to change the file permission of the script. Without proper permission, your script wont run:
chmod +x your_script.sh
chmod +x python_script.py
Open your cron:
The format should be something like this:
00 00 11 * * screen -dmS title sh ~/your_script.sh 00 00 11 * * screen -dmS title sh /home/user/your_script.sh
00 00 11 * * screen -dmS title python3 ~/python_script.py 00 00 11 * * screen -dmS title python3 /home/user/python_script.py