Need to restart apache if apache connection exceeds X amount

Viewed 39

I'm creating a bash script in which whenever my apache exceeds a fixed amount of numbers then it restart itself on next cronjob. I've created something but it is not running properly.

#!/bin/bash
RESTART="systemctl restart httpd"
COUNT="ps aux | grep httpd | wc -l"
SERVICE="httpd"
LOGFILE="/opt/httpd/autostart-apache2.log"



if COUNT > 45
then
echo "starting apache at $(date)" >> $LOGFILE
$RESTART >> $LOGFILE
else
echo "apache is running at $(date)"
fi

The error it is throwing is

line 10: COUNT: command not found
apache is running at Sat Sep 10 23:34:30 IST 2022

Can anyone help me on how to store the value of the output of ps aux | grep httpd | wc -l as a number and compare it with another number.

1 Answers
  • RESTART="systemctl restart httpd" is a variable assignment, although it might work for your use case, you should really use a function instead. See the Complex page for more info.

  • COUNT="ps aux | grep httpd | wc -l" is a variable assignment as well use Command Substitution, like what you did with $(date), on a side note grep has the -c option, there is no need for wc.

  • COUNT > 45 You're executing the COUNT word/string but since there is nothing in your script/path/function/executable with the same name (COUNT is a variable name in your script), thus you get the error: line 10: COUNT: command not found

    • > is a form of redirection if not used in Arithmetic Expression., it truncates a file or create it if it does not exists. Like in your code > 45 created a file named 45. Open the file for writing is the proper term word for it according to the bash manual.

Here is how I would write it.

#!/usr/bin/env bash

service="httpd"
count="$(ps aux | grep -c "$service")"
logfile="/opt/httpd/autostart-apache2.log"
restart(){ systemctl restart  "$service" ; }

if (( count > 45 )); then
  echo "starting apache at $(date)" >> "$logfile"
  restart >> "$logfile" 2>&1
else
  echo "apache is running at $(date)"
fi

  • (( count > 45 )) is a form of test in bash for comparing/testing numbers. The $ can be omitted inside it.
Related