Let me start out by saying I am NOT a script girl. I’ve worked with PHP for a decade and love my use of spacing. I’ve written 1 bash script that clones a database on a remote server and saves the file down and replaces the local database which I was very proud of but I knew it had flaws.
I was asked to create a script to update 500+ files that held cron schedules for each site we host. The hours had to be in a time that was less busy in hopes the sites would have minimal delays on renewing the SSL (a long and weird story for another time). I was told that it should be easy. HA HA HA. Turns out I am not great at scripts so it took longer than what was suggested but it got done.
I learned one big thing during this: bash scripts are sensitive with spaces. This was very annoying to someone who loves front end to look pretty. I had to ask on the StackOverflow forums for help because I was getting nowhere and people helped and it eased my headache.
Without further ado, here’s what I got. Keep these two things in mind. I copied down the 500+ letsencrypt files from the server to my remote to test it. I put them in a folder called renew
and the hours I was aiming for the cron to update was from 2am to noon. Our server is on UTC timezone so this would be in the middle of the night for us on the west coast USA.
#!/bin/bash
for FILE in ./renew/letsenc*
do
[[ -f $FILE && ! -L $FILE ]] && {
# The new cron schedule.
TIMESET="$(($RANDOM % 59 + 0)) $(($RANDOM % 10 + 2))";
# The -i will create a backup file.
sed -i'.bak' -Ee "s/[0-9]+[0-9]+/$TIMESET/" "$FILE";
}
done
echo "Crons have been updated! Moving the backups.";
# Backup folder created if there is none.
mkdir -p ./renew/backups >/dev/null 2>&1
# Create a folder name with the date.
FOLDER_NAME=./renew/backups/$(date +'%Y%b');
mkdir -p $FOLDER_NAME 2>&1
mv ./renew/*.bak $FOLDER_NAME
echo "Done! Have a great day~!";
It took me forever just to get the 1 line to work and that was the sed. Regular expressions are not my thing and the sed file was just not updating the stupid file.
I hope one day this will make sense to me more. I learned to keep spaces around equal signs to a minimal. I was just glad someone else asked that question in another form. -_-