Day4 of #BashBlazeChallenge
Bharat
2 min read
๐ Automated Process Monitoring Script! ๐
Just created a Bash script that ensures a specific process is always up and running on Linux systems. ๐ If the process unexpectedly stops, the script kicks in, automatically restarting it! ๐ ๏ธ
Key Features:
๐ฏ Process Selection: Specify the target process using a command-line argument.
๐ต๏ธโโ๏ธ Process Existence Check: Efficiently checks if the process is currently running.
๐ Restart Mechanism: Automatic restarts initiated when the process is not running.
โฐ Automation: Schedule the script using cron jobs for regular monitoring.
Code :
#!/bin/bash
<<COMMENT1
The script ensures a specific process is always up and running on Linux systems
- Process Selection using a command-line argument.
- Process Existence Check if its runningor not.
- Restart Mechanism : Automatic restarts initiated when the process is not running.
- Automation: Schedule the script using cron jobs for regular monitoring.
COMMENT1
# Function to check is the process is running or not
is_process_running() {
if pgrep -x "$1" >/dev/null; then # if statment evaluates the exit status of the command inside it
return 0
else
return 1
fi
}
# Function restart process
restart_process() {
if sudo systemctl start nginx; then
echo "Process $process_name restarted successfully."
return 0
else
echo "Failed to start the process $process_name."
return 1
fi
}
if [ $# -eq 0 ]; then
echo "Error : Process name not provided in the argument."
exit 1
fi
process_name=$1
max_attempts=3
current_attempt=1
if is_process_running $process_name; then
echo "Process $process_name is currently running."
else
echo "Process $process_name is in STOP state."
read -p "Do you want to Restart the process ? (y/n): " user_input
if [ $user_input = "y" ]; then
while [ $current_attempt -le $max_attempts ];do
echo "Process $process_name is not running. Attempting to restart..."
if restart_process $process_name; then
exit 0
fi
((current_attempt++))
sleep 5
done
echo "Maximum restart attempts reached. Please check the process manually."
else
echo "Thank You."
fi
fi
Output :
0
Subscribe to my newsletter
Read articles from Bharat directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by