Shell 脚本:Grep 用法

Shell Script : Grep usage

我正在尝试终止后台进程 'sleep 600'。为此,我得到了以下运行良好的脚本。

ps -ef | grep "sleep 600" | grep -v grep | awk '{print }' | xargs -I{} kill {}

我想知道 'grep -v grep' 有什么作用?

请您完成以下操作。

ps -ef |                   ##Running ps -ef command to get all running pids information on server, passing its Output to next command as an Input.
grep "sleep 600" |         ##Looking for lines which have sleep 600 in it and sending its output as input to next line.
grep -v grep |             ##grep -v basically omits lines which have string grep in them, since grep command also creates a process to get string in above command so basically it is there to avoid that command's pid.
awk '{print }' |         ##Getting 2nd field of the process and sending it to next command as an Input.
xargs -I{} kill {}         ##Killing pid which was passed from previous command to this one.

来自 man grep:

-v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)

OP 命令改进建议: 您可以删除 grepawk 的多次使用,并且可以在单个 awk 中执行此操作,例如:

ps -ef | awk '/sleep 600/ && !/awk/{print }' | xargs -I{} kill {}

或使用 pkill 选项: 请确保在 运行 之前测试它 PROD/LIVE 环境。此外,在提供模式的同时确保您提供正确的模式以捕获正确的进程,否则它也可能会杀死其他 PID,所以这里只是一个公平的警告。

pkill -f 'sleep 60'

你的命令可以分为几个部分。

  1. ps-ef | grep "sleep 600"

这将尝试在 运行 进程列表中查找睡眠。但问题是,grep 会捕获 grep 本身。

# ps -ef | grep "sleep 600"
fahad     2327 13054  0 12:52 pts/9    00:00:00 sleep 600
root      2463 21217  0 12:52 pts/14   00:00:00 grep --color=auto sleep 600

我们不需要 "grep --color=auto sleep 600" 因为它只是那个命令本身。所以要排除它,我们可以使用 grep -v

grep -v: "-v, --invert-match        select non-matching lines"

因此,在 grep -v 之后加上一个词或其他内容将排除该匹配项。所以在这里你只是选择真正的 sleep 600 过程。

阅读更多有关 grep 的信息:

grep --help

谢谢。