Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top