OK, here's my dilemma, I'm running headless Ubuntu server 18.04.3 LTS on a Dell PowerEdge T710 server, and I'm writing a bash script so that I can easily change the Apache PHP Mod versions without having to keep manually using:-
a2dismod php<version> a2enmod php<version> systemctl restart apache2 The beginning of the script uses an if condition to check if the user is logged in as a user account or a root account using the status bit of UID, ie:-
if ((UID)); then something here elif ((!UID)); then something here fi using ((UID)) to check if the bit is true and using ((!UID) to check if the bit is false, but here's the problem, I want to add a little bit more checking to make sure apache is actually in a running state, I would rather use boolean true or false than to use something like:-
systemctl status apache2 which gives a lot of output. Is there a status bit for apache? Then I can do a check to make sure apache is actually running before continuing the phpmod version change.
This is the script I have so far:
IT not only needs the checking for apache running, but also a check for the various apache PHP modules to make sure they are actually installed before attempting to enable the correct module, and if not, then the script would execute:-
apt install libapache2-mod-php<version> 02 Answers
You can use the is-active unit command of systemctl which “[r]eturns an exit code 0 if at least one [unit] is active, or non-zero otherwise”:
if systemctl is-active --quiet apache2; then echo running else echo not running fi If you’d rather use a parameter there’s $? holding the exit code of the last command, you can simply test for it being 0:
systemctl is-active --quiet apache2 if [ $? -eq 0 ]; then echo running else echo not running fi Further reading
0Defining own exit codes still uses the same logic as @Dessert describes in his answer.
#!/bin/bash systemctl is-active -q apache2 && status=TRUE || status=FALSE case $status in TRUE) echo do something ;; FALSE) echo do sothing else ;; esac 1