#!/bin/bash
function finish {
# Your cleanup code here
}
trap finish EXIT
You place any code that you want to be certain to run in this "finish" function. A good common example: creating a temporary scratch directory, then deleting it after.
#!/bin/bash
scratch=$(mktemp -d -t tmp.XXXXXXXXXX)
function finish {
rm -rf "$scratch"
}
trap finish EXIT
I'm not 100% clear on what you might mean here, but I see two possibilities. A script will normally exit either when the last command it contains is executed, or when an exit statement is explicitly executed. So you don't really have to worry about "making sure it always ends" - by its very nature, a script will end so long as it contains no loop or logic that would cause it to keep running.
However, if what you're meaning here is that you want a command in your script to always exit after a certain amount of time to prevent it from running indefinitely, then you could try something like this:
#!/bin/bash
command="/usr/bin/yes"
maxruntime=10
"$command" >/dev/null 2>/dev/null &
watchpid=$!
/usr/bin/sleep "$maxruntime"
if [ -d "/proc/$watchpid" ]
then
echo "Max runtime exceeded, killing PID $watchpid"
if /bin/kill -9 "$watchpid" >/dev/null 2>/dev/null
then
echo "Killed."
exit 0
else
echo "Could not kill, please investigate manually."
exit 1
fi
fi
Here you define command as the full command you want to run, and maxruntime as the maximum number of seconds it can be permitted to run for. The script then executes the command specified in the variable command in the background, with all output re-directed to /dev/null . It then waits for maxruntime seconds, and if the process still exists, it will attempt to kill it and show you the result.
Note that in its current form the script will always wait for maxruntime seconds no matter what, so even if your command has exited before then the script will wait at least that long. You could amend that easily enough though, but this is just to give you an idea of how this might work.
Hope this helps - if not, or if I've not quite grasped what you're actually struggling with here, then if you could provide a bit more info I'd be happy to help further.
One modification you could make here would be to change the line defining maxruntime to this instead:
maxruntime=$1
The variable $1 has a special meaning referring to the first command-line parameter passed into the script. So for a ten-second timeout, you could then run the script by typing script.sh 10 , and when the script ran maxruntime would take the definition of the first parameter passed to the script - 10, in this case.
I'm not entirely clear on what could have caused a reboot here - from the output you've provided it seems that after five seconds the script proceeded to kill the previously-backgrounded command. If you can give us a bit more info on what went wrong, what necessitated a reboot, and how this came about then I'd be happy to offer further suggestions as to how to proceed.