2

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.

2 Answers 2

3

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\'
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for double quoting and dropping the single quotes from inside the pattern string. However, you should probably point out the second change too.
Edit: Sorry, stackoverflow submitted my comment instead of inserting a newline... Your solution works, thank you! Could you explain to me why '' works when I run the command at the prompt but in my script it requires "" ? Thank you
@alex: this happens because PATTERN doesn't contain literal quote symbols after assignment (they rather indicate that whole expression is single string); to keep treating this expression as a single string, you need to quote it explicitly.
2

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.

1 Comment

The usage message from pgrep shown includes -f without any argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.