0

I am basically trying to see if a service is running and, if not, then start the service. Everything seems to work fine if the service is not running; however, when the service is running, the exact same if condition complains about syntax issues. Here's my example below:

# systemctl status redis-server@openvas.service     
redis-server@openvas.service - Advanced key-value store (openvas)
    Loaded: loaded (/usr/lib/systemd/system/redis-server@.service, disabled)
    Active: inactive (dead)
# if [ ! $(systemctl status redis-server@openvas.service | grep -i "active: active") ]; then systemctl start redis-server@openvas.service; fi 
# systemctl status redis-server@openvas.service
redis-server@openvas.service - Advanced key-value store (openvas)
    Loaded: loaded (/usr/lib/systemd/system/redis-server@.service, disabled)
    Active: active (running)
# if [ ! $(systemctl status redis-server@openvas.service | grep -i "active: active") ]; then systemctl start redis-server@openvas.service; fi
bash: [: active: binary operator expected
# 

How is there a syntax issue all of a sudden if the same command is run before and has no problems?

halfer
  • 19,824
  • 17
  • 99
  • 186
LewlSauce
  • 5,326
  • 8
  • 44
  • 91
  • In most contexts, command substitutions are subject to word-splitting unless double-quoted; so just like variable references, they [should almost always be double-quoted to prevent weirdness](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable). But to test whether a command's output contains a string/pattern, just use `if ! systemctl ... | grep -iq "active: active"`. See: ["Checking if output of a command contains a certain string in a shell script"](https://stackoverflow.com/questions/16931244). – Gordon Davisson Jul 04 '22 at 16:56

1 Answers1

0

Enable debug mode (set -sv) and you should see something like the following:

if [ ! active: active ]; then ...

Which is an invalid test.

In fact, if we run this from the command line we get a similar error message:

$ if [ ! active: active ]; then echo 'here I am'; fi
-bash: [: active:: unary operator expected

# or simulating a subshell call that returns 'active: active'

$ if [ ! $( echo active: active) ]; then echo 'here I am'; fi
-bash: [: active:: unary operator expected

One workaround is to wrap the subshell in double quotes:

$ if [ ! "$( echo active: active)" ]; then echo 'here I am'; fi
$           <= no output; no error msg
markp-fuso
  • 28,790
  • 4
  • 16
  • 36