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.