So recently I was doing doing some bash scripting and required a functionality that would allow my script to wait for for a trigger file in order to execute. After some thinking, I was able to some up with a function to perform the required action.
[topads][/topads]
Basically, how this works is that a function will be looping constantly looking in a specific directory for a specific file to arrive, the function will loop ‘n’ times looking for that specific trigger file, sleeping ‘n’ seconds in between tries. Once found, it fires off the next portion of the script (or a separate script). If the file is not found in ‘n’ times, then will exit with an exit code of 1. You can also set it so it will keep looking for the trigger file indefinitely.
This snippet will also send an email if the trigger file is not found in ‘n’ times.
#!/bin/bash ######################################## # Snippet that waits for a trigger file ######################################## # Script that will send an email ./sendEmail.sh waitForTriggerFile() { TRIGGERFILE=$1 SLEEPTIME=$2 MAXTRIES=$3 # Variables used to send an email SUBJECT="Trigger File Not Found" EMAIL="$4" EMAILMESSAGE="mailMessage.txt" if [[ ! -f $TRIGGERFILE ]]; then count=0 while [[ ! -e $TRIGGERFILE ]]; do let count=count+1 if [[ $count == $MAXTRIES ]]; then # Sends an email if can't file trigger file in 'n' times sendMail $SUBJECT $EMAIL $EMAILMESSAGE exit 1 fi echo "Will check again in $SLEEPTIME seconds" sleep $SLEEPTIME done # Execute another script fi # Execute another script }
In above code ‘sendMail’ is a function in ‘sendMail.sh’ that accepts three arguments: subject, email, and a text file for the email message. You can view the snippet here: send email snippet
Hope this was helpful to you…
Share this article 🙂
[bottomads][/bottomads]
Wait For #TriggerFile – #Unix #Shell #Snippet #Linux http://t.co/VwopMET5
hello very cool post man!