我写了一个小脚本,出于某种原因,我需要转义参数中传递的任何空格以使其正常工作。
我阅读了许多其他关于有此问题的人的文章,这通常是由于没有引用 $@,但我的所有变量都在脚本中引用,并且在命令行中也引用了参数。此外,如果我在调试模式下运行脚本,则返回的行可以通过复制粘贴成功运行,但在脚本内执行时会失败。
代码:
connections ()
{
args="$@"
pid="$(pgrep -nf "$args")"
echo $pid
# code that shows TCP and UDP connections for $pid
}
connections "$@"
例子:
bash test.sh "blah blah"
失败,而是返回当前运行的 shell 的 pid
bash test.sh "blah\ blah"
成功并返回您通过 pgrep 搜索的进程的 pid