Bash script that exits after specified time


I want to share with you a script I wrote. It’s about quitting/killing your script process after X seconds, managed entirely by you. You should know that bash in not “smart”. Doing arithmetic operations can be painful. I needed a script which collect MySQL processlists. Of course this can be done manually but the thing is that I needed this to start on Monday, 1 AM. I am too lazy and sleepy to work at night. And I couldn’t risk to put a script in the crontab without exiting after the needed time. I cannot be sure how big logs I will collect. That’s why I wanted my script to finish at 3:00 AM.



echo “_______________________________________”
echo “|                                                                            |”
echo “|Logging full processlist every second!               |”
echo “|______________________________________|”

UNIX_TIME_NOW=$(date +%s)

while [ “$UNIX_TIME_LIMIT” -gt “$UNIX_TIME_NOW” ];
NOW=`date ‘+%Y-%m-%d__%T’`
mysql -u -p -e “show full processlist” | grep -v ‘Sleep’ | tee -a /your/dir/plist-$NOW.log
sleep 2s
UNIX_TIME_NOW=$(date +%s)


What the script does is calculating current time and adding extra time set by me. When the clock measures EXTRA_TIME the script will exit.

2 thoughts on “Bash script that exits after specified time

Leave a Reply

Your email address will not be published. Required fields are marked *