如何在 shell 别名中的 awk 语句中转义“$”

如何在 shell 别名中的 awk 语句中转义“$”

我正在尝试编写一个别名来终止所有正在运行的 php 进程。这是我在~/.bash_profile

alias killphp="ps aux | g [p]hp | awk '{print $3}' | xargs kill -9"

如果我按原样输入而不使用别名,这个命令就可以正常工作。但如果我只是运行,killphp就会出现这种奇怪的情况:

grep: warning: recursive search of stdin
kill: illegal process id: (standard
kill: illegal process id: input):2:abdullah
kill: illegal process id: 10.9
kill: illegal process id: 0.2
kill: 2496576: No such process
kill: 20460: No such process
kill: illegal process id: ??
kill: illegal process id: S
kill: illegal process id: 7:14AM
kill: illegal process id: 0:00.28
kill: illegal process id: /usr/local/Cellar/php54/5.4.28/bin/php
kill: illegal process id: /Users/abdullah/dev/php/smartTaxi/app/console
kill: illegal process id: bcc:resque:worker-start
kill: illegal process id: -f
kill: illegal process id: request_queue
kill: illegal process id: --env=dev
kill: illegal process id: (standard
kill: illegal process id: input):3:abdullah
kill: illegal process id: 6.0
kill: illegal process id: 0.1
kill: 2486972: No such process
kill: 9708: No such process
kill: illegal process id: ??
kill: illegal process id: S
kill: illegal process id: 7:14AM
kill: illegal process id: 0:00.08
kill: illegal process id: php
kill: illegal process id: /Users/abdullah/dev/php/smartTaxi/app/../vendor/chrisboulton/php-resque/resque.php

如果我运行type killphp我会得到这个:

killphp is aliased to `ps aux | g [p]hp | awk '{print }' | xargs kill -9'

因此,显然$3awk 的参数已经消失!我该如何摆脱它?我尝试过/$3$$3但都不起作用。

答案1

您最好使用pkill。但要解决您的问题,请killphp通过将其放入您的配置文件中来创建一个 bash 函数而不是别名。

killphp() {
  ps aux | g [p]hp | awk '{print $3}' | xargs kill -9
}

然后您就可以像别名一样使用它:

killphp

$您可以通过编写来逃避\$,但使用函数时您不必担心引用。

相关内容