Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Directory where Systemd files will be stored
- SYSTEMD_DIR="/etc/systemd/system"
- # Path to the crontab file
- CRONTAB_FILE="/etc/crontab"
- # Function to convert cron syntax to Systemd OnCalendar syntax
- convert_cron_to_systemd_timer() {
- minute="$1"
- hour="$2"
- day_of_month="$3"
- month="$4"
- day_of_week="$5"
- echo "$month-$day_of_month *-$day_of_week $hour:$minute:00"
- }
- # Main function
- process_crontab() {
- while read -r line; do
- # Skip comments, empty lines, and lines with environment variables
- if [[ "$line" =~ ^# ]] || [[ -z "$line" ]] || [[ "$line" =~ ^[A-Za-z_]+= ]]; then
- continue
- fi
- # Check if the line has at least 6 fields for the time specs and the command
- fields=($line)
- if [[ ${#fields[@]} -lt 6 ]]; then
- continue
- fi
- # Parse the line (first part is the time specs, last part is the command)
- minute="${fields[0]}"
- hour="${fields[1]}"
- day_of_month="${fields[2]}"
- month="${fields[3]}"
- day_of_week="${fields[4]}"
- command="${fields[@]:5}"
- # Create a timer name based on the command
- timer_name=$(basename "$command" | sed 's/\..*//')
- # Create the Systemd .service file
- echo "[Unit]
- Description=Run $command from cron
- [Service]
- ExecStart=$command
- " > "$SYSTEMD_DIR/$timer_name.service"
- # Create the Systemd .timer file
- calendar=$(convert_cron_to_systemd_timer "$minute" "$hour" "$day_of_month" "$month" "$day_of_week")
- echo "[Unit]
- Description=Timer for $timer_name
- [Timer]
- OnCalendar=$calendar
- Persistent=true
- [Install]
- WantedBy=timers.target
- " > "$SYSTEMD_DIR/$timer_name.timer"
- # Enable and start the timer
- systemctl enable "$timer_name.timer"
- systemctl start "$timer_name.timer"
- echo "Created and started $timer_name.timer"
- done < "$CRONTAB_FILE"
- }
- # Execution
- process_crontab
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement