How To Write Bash Scripts In Linux - Complete Guide (Part 15 - CRON Jobs)
Scheduling Bash Scripts with Cron
Introduction to Scheduling Jobs
- The video focuses on scheduling bash scripts to run at a future time, building upon previous lessons about job scheduling.
- The instructor will use the same script from the prior lesson but will demonstrate how to schedule it using cron instead of the
atcommand.
Best Practices for Script Commands
- A key change involves using fully qualified commands in scripts (e.g.,
/usr/bin/echoinstead of justecho) for better reliability and security.
- The
whichcommand is introduced as a tool to find the full path of commands, ensuring that scripts can locate them correctly when executed by cron.
- Using fully qualified paths helps avoid issues where cron may not recognize commands due to different shell environments or path variables.
Security Considerations
- There are security risks associated with not using fully qualified commands; malicious scripts could be named identically to legitimate ones, leading to potential data loss or system damage.
- While having root access could allow an attacker to replace legitimate commands, using full paths minimizes this risk by specifying exactly which command should be executed.
Editing Crontab
- To edit crontab, the command
crontab -eis used. This opens the user's crontab file in a text editor (defaulting to Nano).
- Comments within crontab files provide guidance on how jobs are structured and what each field represents.
Understanding Crontab Syntax
- Each line in a crontab follows a specific format: minute, hour, day of month, month, day of week followed by the command path.
- An example is given where a script runs every Friday at 1:30 AM. Adjusting fields allows for more granular control over when tasks execute.
Saving and Validating Crontab Entries
- After editing, saving the file checks syntax validity. However, if referenced scripts do not exist at specified locations, they won't run successfully despite valid syntax.
Managing Other Users' Crontabs
- To edit another user's crontab, one can use
sudo crontab -e -u username, requiring root privileges for access.
Conclusion and Next Steps
- Viewers are encouraged to practice scheduling jobs with cron and explore its utility in automating tasks without manual intervention.