detect shutdown state from bash script


Go to solution Solved by apandey,

Recommended Posts

Hi

 

I have a bash script that starts with the array and continues running in a while loop.

 

This script is preventing my server from shutting down (if I kill the script manually shutdown works as expected).

 

What's the most efficient way to detect a shutdown state from within the bash script so I can have it self terminate?

 

Something like:

 

if exists /tmp/shutdown.txt; then exit 1; fi 

 

Many thanks

Edited by ThatDude
more info
Link to comment
  • Solution
2 hours ago, ThatDude said:

What's the most efficient way to detect a shutdown state from within the bash script so I can have it self terminate?

You should trap SIGTERM and terminate when you see it. How you do it is up to you - set a poison pill variable or kill $$

 

EDIT: SIGTERM is sent to process initially on shutdown, but a SIGKILL is also sent subsequently. So just make your script handle the signals properly

Edited by apandey
  • Like 1
Link to comment
10 hours ago, apandey said:

You should trap SIGTERM and terminate when you see it. How you do it is up to you - set a poison pill variable or kill $$

 

EDIT: SIGTERM is sent to process initially on shutdown, but a SIGKILL is also sent subsequently. So just make your script handle the signals properly

 

Thank you.

 

SIGINT was the missing part of the puzzle, I've never come across that before.

 

 
#!/bin/bash
exit_script() {
    trap - SIGINT SIGTERM # clear the trap
    kill -- -$$ # Sends SIGTERM to child/sub processes
}

trap exit_script SIGINT SIGTERM

while true; do
    echo "Do some task"
done

 

Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.