alex
alex

Reputation: 131

bash script/pgrep not working as expected

I have a bash script that tries to call pgrep with arguments (Over simplified):

PATTERN="'/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf\$'"
pgrep -f $PATTERN
echo pgrep -f $PATTERN

Gives the following output:

Usage: pgrep [-cflvx] [-d DELIM] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
        [-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]
pgrep -f '/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'

I suppose it means the argument is not passed to pgrep but is passed to echo for some reason.

What I'm expecting:

7632
pgrep -f '/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'

When I run the preg line by itself, it outputs 7632 as expected.

Am I doing something wrong here? I've tried with sh, dash and bash. Same outcomes, I really don't see the problem.

Upvotes: 2

Views: 6219

Answers (2)

barti_ddu
barti_ddu

Reputation: 10299

You need to surround PATTERN in double quotes:

PATTERN="/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf\$"
pgrep -f "$PATTERN"

See: quoting variables

Edit: and for echoing i would just do:

echo pgrep -f \'$PATTERN\'

Upvotes: 3

shellter
shellter

Reputation: 37268

As I don't have lighttpd.bin available to test with, I am submitting an untested option, mostly agreeing with @barti_ddu, but with a slightly different twist

PATTERN='/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf\$'
pgrep  -f "$PATTERN"
echo pgrep  -f "$PATTERN"

I would keep the single quotes on the assingment to PATTERN, but totally agree you need the dbl-quoting when using with pgrep or echo.

I hope this helps.

Upvotes: 2

Related Questions