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
"$@"
is not the problem. But I still don't see why you want to misuse it - ruakh 2012-04-03 23:50
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
.
"$@"
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 topgrep -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