Advertisement
Guest User

Untitled

a guest
Aug 26th, 2024
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Directory where Systemd files will be stored
  4. SYSTEMD_DIR="/etc/systemd/system"
  5.  
  6. # Path to the crontab file
  7. CRONTAB_FILE="/etc/crontab"
  8.  
  9. # Function to convert cron syntax to Systemd OnCalendar syntax
  10. convert_cron_to_systemd_timer() {
  11. minute="$1"
  12. hour="$2"
  13. day_of_month="$3"
  14. month="$4"
  15. day_of_week="$5"
  16.  
  17. echo "$month-$day_of_month *-$day_of_week $hour:$minute:00"
  18. }
  19.  
  20. # Main function
  21. process_crontab() {
  22. while read -r line; do
  23. # Skip comments, empty lines, and lines with environment variables
  24. if [[ "$line" =~ ^# ]] || [[ -z "$line" ]] || [[ "$line" =~ ^[A-Za-z_]+= ]]; then
  25. continue
  26. fi
  27.  
  28. # Check if the line has at least 6 fields for the time specs and the command
  29. fields=($line)
  30. if [[ ${#fields[@]} -lt 6 ]]; then
  31. continue
  32. fi
  33.  
  34. # Parse the line (first part is the time specs, last part is the command)
  35. minute="${fields[0]}"
  36. hour="${fields[1]}"
  37. day_of_month="${fields[2]}"
  38. month="${fields[3]}"
  39. day_of_week="${fields[4]}"
  40. command="${fields[@]:5}"
  41.  
  42. # Create a timer name based on the command
  43. timer_name=$(basename "$command" | sed 's/\..*//')
  44.  
  45. # Create the Systemd .service file
  46. echo "[Unit]
  47. Description=Run $command from cron
  48.  
  49. [Service]
  50. ExecStart=$command
  51. " > "$SYSTEMD_DIR/$timer_name.service"
  52.  
  53. # Create the Systemd .timer file
  54. calendar=$(convert_cron_to_systemd_timer "$minute" "$hour" "$day_of_month" "$month" "$day_of_week")
  55. echo "[Unit]
  56. Description=Timer for $timer_name
  57.  
  58. [Timer]
  59. OnCalendar=$calendar
  60. Persistent=true
  61.  
  62. [Install]
  63. WantedBy=timers.target
  64. " > "$SYSTEMD_DIR/$timer_name.timer"
  65.  
  66. # Enable and start the timer
  67. systemctl enable "$timer_name.timer"
  68. systemctl start "$timer_name.timer"
  69.  
  70. echo "Created and started $timer_name.timer"
  71. done < "$CRONTAB_FILE"
  72. }
  73.  
  74. # Execution
  75. process_crontab
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement