Starting a Screen Sessions Upon Reboot and Executing a Script in It

Abstract: Configure cron to automatically start a named GNU Screen session and execute a script upon system reboot.

Created: 2026-08-19 by
To automatically start a GNU Screen session and execute a script upon reboot, you must configure the system’s cron daemon to run the command at boot time. By using the @reboot directive within the crontab file, you can trigger a shell script that launches the screen environment with your specific program attached. This approach ensures that background processes persist through reboots without requiring manual intervention or a persistent login session.

Understanding the Cron Daemon and Reboot Triggers

The cron service is the standard job scheduler in Linux distributions like Ubuntu. While it typically handles tasks based on minutes, hours, or days, it also supports special strings for system events. The @reboot string is particularly useful for initializing services or running scripts immediately after the kernel has finished loading but before user logins are required. Using @reboot is generally preferred over placing commands in /etc/rc.local because cron provides better logging and error handling. When a cron job fails, the output is often captured in mail spools or system logs, allowing you to diagnose issues more easily than with legacy init scripts. Furthermore, cron jobs run under the context of the user who owns the crontab, which helps isolate permissions and environment variables.

Preparing the Execution Script

Before configuring the scheduler, you need a robust shell script that will handle the creation of the screen session. It is best practice to write this script separately so you can test it manually before relying on the automated trigger. Create a file named start_screen.sh in a directory accessible by your user, such as /home/username/scripts/. Inside this script, you should define the path to the screen binary and the script or command you wish to run. You must also ensure that the screen session does not detach immediately after starting. The following structure demonstrates how to create a named session and attach a command to it:
#!/bin/bash

# Define variables
SCREEN_NAME="my_background_task"
COMMAND_TO_RUN="/usr/bin/my_application --arg1 --arg2"

# Check if the session already exists to prevent duplicates
if ! screen -list | grep -q "$SCREEN_NAME"; then
    # Start a new detached screen session with the specified name
    screen -dmS "$SCREEN_NAME" $COMMAND_TO_RUN
fi
This script uses the -dmS flags. The -d flag starts the session in "detached" mode, meaning it runs in the background. The -m flag forces screen to create a new session even if stdin is not a terminal. The -S flag assigns a unique name to the session, making it easy to identify later via screen -list. Always ensure this script is executable by running chmod +x /home/username/scripts/start_screen.sh.

Configuring the Crontab Entry

Once your script is ready and tested, you need to add it to the user’s crontab. Open the editor by typing crontab -e in your terminal. If this is your first time editing, select your preferred text editor. Add the following line to the bottom of the file:
@reboot /home/username/scripts/start_screen.sh >> /home/username/logs/cron_boot.log 2>&1
The >> operator appends any output from the script to a log file, while 2>&1 redirects standard error to standard output. This ensures that if the screen command fails or produces warnings, you have a record of what happened during the boot process. It is crucial to use absolute paths for both the script and the log file, as the cron environment does not inherit your current working directory or full $PATH variable. For more information on securing your server setup against unauthorized access, consider reviewing our guide on Securing an Ubuntu Server for Development Purposes, which covers essential hardening steps that complement automated task management.

Verifying the Setup

After saving the crontab, you can verify that the entry was added correctly by running crontab -l. To test the logic without waiting for a reboot, you can manually execute the script and check if the screen session appears. Use screen -ls to list active sessions. If the session is listed, your configuration is likely correct.

Troubleshooting Common Issues

If the script does not run at boot, the most common cause is incorrect permissions or missing environment variables. Cron jobs do not load the same environment as your interactive shell. If your script relies on specific libraries or tools located in non-standard directories, you may need to source a profile file at the beginning of your script or use absolute paths for every command. Another frequent issue is the lack of a display variable. While screen itself does not strictly require a graphical display, some applications launched within it might. Ensure that your script does not attempt to open GUI windows unless a virtual framebuffer is configured. Additionally, check the system journal using journalctl -xe around the time of boot to see if the cron daemon encountered any errors executing your job. For users interested in optimizing system performance alongside these background tasks, understanding how the OS manages resources is key. You might find our article on Ubuntu Kernel Sending Task to Isolated Core helpful for fine-tuning CPU affinity for heavy background processes.

Frequently Asked Questions

Can I use systemd instead of cron for this task?

Yes, creating a systemd service unit is often a more modern and robust alternative to cron for managing long-running processes. Systemd allows you to define dependencies, restart policies, and logging more granularly than cron's simple execution model. However, cron is simpler to configure for basic one-off startup scripts.

Why is my screen session not appearing when I log in?

Screen sessions created with -dm (detached) will not automatically attach to your terminal upon login. You must manually attach to them using screen -r my_background_task. If the session died immediately, check the log file you redirected the output to, as the application inside may have crashed due to missing dependencies.

How do I stop the screen session if it gets stuck?

You can kill the screen session directly from the command line using screen -X -S my_background_task quit. Alternatively, if you are inside the screen session, you can type exit or press Ctrl+A followed by \ to kill the entire window. Be cautious, as this will terminate the underlying process running inside the session.

Does @reboot work for all users?

The @reboot directive works for any user who has permission to edit their own crontab via crontab -e. Root users can also schedule jobs at reboot, but they must be careful about environment variables and security implications. Regular users cannot schedule jobs for other users without sudo privileges.

What happens if the script fails to start?

If the script fails, cron will typically send an email to the user associated with the crontab if mail is configured on the system. Since we redirected output to a log file in our example, checking that specific log file is the primary way to diagnose failures. Without logging, silent failures are common, making logging an essential step in automation.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More