pgrep prints a different pid than expected

Go To StackoverFlow.com

1

I wrote a small script and for some reason I need to escape any spaces passed in parameters to get it to work.

I read numerous other articles about people with this issue and it is typically due to not quoting $@, but all of my variables are quoted within the script and the parameters quoted on the command line as well. Also, if I run the script in debug mode the line that is returned can be run successfully via copy paste but fails when executed from within the script.

CODE:

connections ()
{
    args="$@"
    pid="$(pgrep -nf "$args")"
    echo $pid
    # code that shows TCP and UDP connections for $pid
}
connections "$@"

EXAMPLE:

bash test.sh "blah blah"

fails and instead returns the pid of the currently running shell

bash test.sh "blah\ blah"

succeeds and returns the pid of the process you are searching for via pgrep

2012-04-03 21:50
by Michael Hogg
This isn't your problem, exactly, but I don't quite understand your use of "$@" here. connections seems clearly designed to take only a single argument, and it will misbehave if it receives multiple arguments (in that it will pass all of those arguments separately to pgrep -nf, such that the first argument is matched against the command line and all subsequent arguments are matched only against the process name). So why not just use "$1" instead? Or, better yet, give some sort of error or warning if there are multiple arguments - ruakh 2012-04-03 22:13
I already attempted that and had the same issue. If i replace all instances of $@ with $1 the same issue is experienced(escaping the space works, while not escaping the space pulls the pid of the current shell - Michael Hogg 2012-04-03 22:25
Yes: as I said, your misuse of "$@" is not the problem. But I still don't see why you want to misuse it - ruakh 2012-04-03 23:50


1

Your problem has nothing to do with "$@".

If you add a -l option to pgrep, you can see why it's matching the current process.

The script you're running also includes what you're trying to search for in its own arguments.

It's like doing this, and seeing grep:

$ ps -U $USER -o pid,cmd | grep gnome-terminal
12410 grep gnome-terminal
26622 gnome-terminal --geometry=180x65+135+0

The reason the backslash makes a difference? pgrep thinks backslash+space just means space. It doesn't find your script, because that contains blah\ blah, not blah blah.

2012-04-04 01:25
by Mikel
Ads