new shell script calling restartsrv httpd

jimlongo

Well-Known Member
Mar 20, 2008
242
20
68
Hi, I've developed a script to check for new VERSION of Atomic Rules and update if necessary.

I've tested that to my satisfaction, however the part that makes me a little nervous is the restart of Apache.

currently I'm storing a variable and then calling that at the end of the script

Code:
RESTART_APACHE="/usr/local/cpanel/scripts/restartsrv httpd"
...
if ! $RESTART_APACHE; then
	echo "ERROR: Apache did not restart properly!"
	exit 1
fi
Is that a safe approach?
 

KostonConsulting

Well-Known Member
Verifed Vendor
Jun 17, 2010
255
1
68
San Francisco, CA
cPanel Access Level
Root Administrator
A couple of things. If you're trying to execute the command and capture its output, use this command:

Code:
RESTART_APACHE=$(/usr/local/cpanel/scripts/restartsrv httpd)
Double quotes just saves the string to the variable.

Now, before restarting Apache, you'll want to ensure you have little to no chance to bring it down. So, I'd recommend testing to ensure the config is not broken. You can check this with:

/usr/local/apache/bin/apachectl configtest

It will output 'Syntax OK' if there are no errors but you may get false positives as it can output warnings for duplicate virtualhosts and such so you may need to tweak which patterns are allowed.

Code:
APACHE_CONFIG=$(/usr/local/apache/bin/apachectl configtest 2>&1)
if [[ $APACHE_CONFIG =~ "Syntax OK" ]]; then
    echo "Apache config is ok."
else
    echo "Apache config problem"
fi

Restarting Apache via the cPanel script gives this type output:

# /usr/local/cpanel/scripts/restartsrv httpd
Waiting for httpd to restart.....finished.

httpd (/usr/local/apache/bin/httpd -k start -DSSL) running as root with PID 25532 (process table check method)

Apache successfully restarted.


So, you'll want to test for the key phrase 'Apache successfully restarted', like so:

Code:
RESTART_APACHE=$(/usr/local/cpanel/scripts/restartsrv httpd)

if [[ $RESTART_APACHE =~ "Apache successfully restarted" ]]; then
    echo "Apache restarted successfully"
else 
    echo "Apache restart failed: $RESTART_APACHE" 
fi
So, putting in the configtest check first gives you:

Code:
#!/bin/bash
APACHE_CONFIG=$(/usr/local/apache/bin/apachectl configtest 2>&1)
 
if [[ $APACHE_CONFIG =~ "Syntax OK" ]]; then
    echo "Apache config is ok. Restarting Apache."

    RESTART_APACHE=$(/usr/local/cpanel/scripts/restartsrv httpd)

    if [[ $RESTART_APACHE =~ "Apache successfully restarted" ]]; then
        echo "Apache restarted successfully"
    else
        echo "Apache restart failed: $RESTART_APACHE"
    fi
else
    echo "Apache config problem. Will not restart apache: $APACHE_CONFIG"
fi