Q:

Escaping variable in grep statement in conditional statement

I have a script with this line:
if [ -z "`/sbin/service mysqld status | grep 'mysqld (.*) is running'`" ] ; then

I want to replace the service name and the grep regex with a variable. Different versions of OS/MySQL have different service names and report different statuses. I'm tired of editing the line in the code. So I did this:
SERVICE_NAME=mysql
SERVICE_RUNNING_STR="MySQL (.*) running"
...
if [ -z "`/sbin/service $SERVICE_NAME status | grep '$SERVICE_RUNNING_STR'`" ] ; then
...

Except it doesn't work. It outputs SERVICE_RUNNING_STR in the grep statement. I've tried many combinations of quotes and other things and haven't got it to work. I'm not sure what it takes being embedded in quotes and ticks and single quotes.

A:

Do not use single quotes, they do not expand variables. Backslash the doublequotes:
[ -z "`/sbin/service $SERVICE_NAME status | grep \"$SERVICE_RUNNING_STR\"`" ] 

